I like to use Java 8 Comparator
to sort a List
of an object based on three properties. The requirement is to sort in this order - Name ascending, Age descending, City ascending. If I use reversed()
on `Age it reverses previously sorted entries as well. Here is what I've tried:
Comparator.comparing((Person p) -> p.getName())
.thenComparingInt(p -> p.getAge())
.reversed()
.thenComparing(p -> p.getCity());
1. Creating Comparators for Multiple Fields. To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.
reflect. Field is used to compare two field objects. This method compares two field objects and returns true if both objects are equal otherwise false. The two Field objects are considered equal if and only if when they were declared by the same class and have the same name and type.
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.
Use Comparator.reverseOrder()
:
.thenComparing(Person::getAge, Comparator.reverseOrder())
If you want to avoid autoboxing, you can do
.thenComparing((p1, p2) -> Integer.compare(p2.getAge(), p1.getAge()))
Or
.thenComparing(Comparator.comparingInt(Person::getAge).reversed())
There is no need to use the method Comparator::reverse
. Since you want to reverse the comparison based on the integer, just negate the age -p.getAge()
and it will be sorted in the descending order:
Comparator.comparing((Person p) -> p.getName())
.thenComparingInt(p -> -p.getAge())
.thenComparing(p -> p.getCity());
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