Java 8 – Compare multiple fields in different order using Comparator

  • A+
Category:Languages

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 -> e.getAge())           .reversed()           .thenComparing(p -> p.getCity()); 

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: