简体   繁体   中英

Java 8 - Compare multiple fields in different order using Comparator

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM