我喜欢使用Java 8 Comparator
根据三个属性对对象的List
进行排序。要求是按此顺序排序-名称升序,年龄降序,城市升序。如果我在`Age'上使用reversed()
,它也会颠倒先前排序的条目。这是我尝试过的:
Comparator.comparing((Person p) -> p.getName())
.thenComparingInt(p -> p.getAge())
.reversed()
.thenComparing(p -> p.getCity());
答案 0 :(得分:11)
使用Comparator.reverseOrder()
:
.thenComparing(Person::getAge, Comparator.reverseOrder())
如果要避免自动装箱,可以执行
.thenComparing((p1, p2) -> Integer.compare(p2.getAge(), p1.getAge()))
或
.thenComparing(Comparator.comparingInt(Person::getAge).reversed())
答案 1 :(得分:6)
不需要使用方法Comparator::reverse
。由于您想基于整数反转比较,因此只需取消年龄-p.getAge()
,它将按降序排序:
Comparator.comparing((Person p) -> p.getName())
.thenComparingInt(p -> -p.getAge())
.thenComparing(p -> p.getCity());