0

I want to sort this list of Emp objects in ascending order based on the marks field.

List<Emp> emp= new ArrayList<Emp>();

public class Emp implements Serializable {
    private String empname;
    private String section;
    private int empId;
    private int marks;
    ...
nbrooks
  • 18,126
  • 5
  • 54
  • 66
yusuf
  • 73
  • 1
  • 9

3 Answers3

2

You need to write a comparator, otherwise the Sort method assumes which fields you want use when sorting.

 Collections.sort(emp, new Comparator<Emp>() { public int compare(Emp one, Emp two) {
       return one.marks.compareTo(two.marks);
  });

In my example i treated the field marks as public, replace one.marks with a getter if you so choose.

Also since you're using ints which do not have a compareTo, do like so:

     Collections.sort(list, new Comparator<Emp>() {
       public int compare(Emp one, Emp two) {
           int cmp = one.getMarks() > two.getMarks() ? +1 : one.getMarks() < two.getMarks() ? -1 : 0;
           return cmp;
       }
   });
zmf
  • 9,095
  • 2
  • 26
  • 28
1

You can use a comparator object to sort.

Collections.sort();

does the sorting.

This will work with your List. The method to be used is compareTo.

    if (list.size() > 0) {
    Collections.sort(list, new Comparator<Emp>() {
        @Override
        public int compare(final Emp object1, final Emp object2) {
            return object1.getMarks().compareTo(object2.getMarks());
        }
       } );
   }
sTg
  • 4,313
  • 16
  • 68
  • 115
0

There are two main ways of supporting object comparisons in Java.

You can have your class implement the Comparable interface, which is acceptable when your objects have a natural ordering that you're relying on (for example, alphabetical ordering for strings). This requires classes to implement a compareTo method which defines the comparison rule between instances.

The standard alternative is to instantiate a Comparator for your class, and specify the comparison rule in a compare method.

In your case, the latter option seems more appropriate. The mechanics of the compare method are fairly simple: it takes two instances of your class, returns a negative value if the first is "less than" the second, a positive number if it is "greater", and 0 if they are "equal". For integer-based comparisons, like comparing by marks, the quick trick is to return the difference of the numbers.

Once you have your Comparator defined, sorting is as simple as invoking the Collections.sort method, opting for the method signature which takes a List and a specified Comparator.

List<Emp> emps = new ArrayList<Emp>();
// populate list...

Comparator<Emp> empComparator = new Comparator<Emp>() {
    public int compare(Emp e1, Emp e2) {
        return e2.getMarks() - e2.getMarks();
    }
};

Collections.sort(emps, empComparator);
nbrooks
  • 18,126
  • 5
  • 54
  • 66