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; }
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() .
Change the last bit to:
.thenComparing(Student::getID, Comparator.reverseOrder())
Or, if you want to avoid autoboxing:
.thenComparing(Comparator.comparingInt(Student::getID).reversed())
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; }
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