I want to sort my objects in descending order using comparator.
class Person { private int age; }
Here I want to sort a array of Person objects.
How can I do this?
In order to sort ArrayList in Descending order using Comparator, we need to use the Collections. reverseOrder() method which returns a comparator which gives the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
TreeSet<Integer> treeSetObj = new TreeSet<Integer>( Collections. reverseOrder() ) ; Collections. reverseOrder() is used to obtain a comparator in order to reverse the way the elements are stored and iterated.
The Comparator and Comparable interface don't do any sorting, so there is no sorting algorithm there. They just compare two Objects, something you need if you want to sort a list of those objects.
Java Comparator interface is used to order the objects of a user-defined class. This interface is found in java. util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).
You can do the descending sort of a user-defined class this way overriding the compare() method,
Collections.sort(unsortedList,new Comparator<Person>() { @Override public int compare(Person a, Person b) { return b.getName().compareTo(a.getName()); } });
Or by using Collection.reverse()
to sort descending as user Prince mentioned in his comment.
And you can do the ascending sort like this,
Collections.sort(unsortedList,new Comparator<Person>() { @Override public int compare(Person a, Person b) { return a.getName().compareTo(b.getName()); } });
Replace the above code with a Lambda expression(Java 8 onwards) we get concise:
Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));
As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :
personList.sort((a,b)->b.getName().compareTo(a.getName()));
Here a
and b
are inferred as Person type by lambda expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With