Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting using Comparator- Descending order (User defined classes) [closed]

Tags:

java

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?

like image 872
Manoj Avatar asked Dec 22 '09 14:12

Manoj


People also ask

How do you make a Comparator with descending order?

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.

How do you sort TreeSet in descending order in Java using Comparator?

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.

Which sorting algorithm is used in Comparator?

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.

Which classes have Comparator () method?

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).


1 Answers

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.

like image 151
Lucky Avatar answered Sep 19 '22 18:09

Lucky