[英]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. 我喜欢使用Java 8 Comparator
基于三个属性对对象的List
进行排序。 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. 如果我在Age上使用reversed()
,它也会反转先前排序的条目。 Here is what I've tried: 这是我尝试过的:
Comparator.comparing((Person p) -> p.getName())
.thenComparingInt(p -> p.getAge())
.reversed()
.thenComparing(p -> p.getCity());
Use Comparator.reverseOrder()
: 使用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
. 无需使用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: 由于您希望基于整数反转比较,只需取消年龄-p.getAge()
,它将按降序排序:
Comparator.comparing((Person p) -> p.getName())
.thenComparingInt(p -> -p.getAge())
.thenComparing(p -> p.getCity());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.