Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Comparator chaining with a reverse on single property

Tags:

I am using a Comparator to sort a list of Student objects.

I want to reverse the sorting on the id property, but using reverse() method applies it on the whole sorting.

How to make it happens only on the id?

Here's my code so far:

 public List<Student> getStudents(List<String> events) {     Comparator<Student> comparatorStudents = Comparator.comparing(Student::getCGPA).thenComparing(Student::getName)       .thenComparingInt(Student::getID).reverse();     List<Student> students = new ArrayList<Student>();     //Filling students     Collections.sort(students, comparatorStudents);     return students;   } 
like image 401
Logan Wlv Avatar asked Jun 18 '18 19:06

Logan Wlv


People also ask

How do you reverse Comparator comparison?

You can use Comparator. reverseOrder() to have a comparator giving the reverse of the natural ordering. If you want to reverse the ordering of an existing comparator, you can use Comparator. reversed() .


2 Answers

Change the last bit to:

.thenComparing(Student::getID, Comparator.reverseOrder()) 

Or, if you want to avoid autoboxing:

.thenComparing(Comparator.comparingInt(Student::getID).reversed()) 
like image 125
shmosel Avatar answered Oct 03 '22 08:10

shmosel


Put the call of reversed() inside thenComparing:

public List<Student> getStudents(List<String> events) {     Comparator<Student> comparatorStudents = Comparator.comparing(Student::getCGPA)        .thenComparing(Student::getName)        .thenComparing(Comparator.comparingInt(Student::getID).reversed());     List<Student> students = new ArrayList<Student>();     //Filling students     Collections.sort(students, comparatorStudents);     return students; } 
like image 21
Sergey Kalinichenko Avatar answered Oct 03 '22 07:10

Sergey Kalinichenko