gpt4 book ai didi

java - 使用1.8 jdk按多个字段对对象列表进行排序

转载 作者:行者123 更新时间:2023-12-01 19:55:08 24 4
gpt4 key购买 nike

我收集了一些人:

class Person {
public String name;
public int count;
public boolean favorite;

// getters / setters ...
}

我想按以下方式对人员集合进行排序:

  1. 首先显示 favorite=true 的项目
  2. 第二个显示数量 > 0 的项目
  3. 最后显示的项目数量 == 0

如何使用 1.8 JDK 中的比较器编写此条件并检索预期结果?

最佳答案

您可以使用Comparator.comparing(...).thenComparing(...)按多个属性排序。要首先对 Collection 夹进行排序,您可以按该属性排序,但随后必须反转结果,如 false排序在 true 之前。假设您只想按是否 count 进行排序是 > 0 ,而不是计数的实际值:

List<Person> persons = Arrays.asList(
new Person("p1", 2, true),
new Person("p2", 0, false),
new Person("p3", 0, true),
new Person("p4", 1, false),
new Person("p5", 3, true));

persons.stream().sorted(Comparator
.comparing(Person::isFavorite).reversed()
.thenComparing(p -> p.getCount() == 0))
.forEach(System.out::println);

结果:

Person(name=p1, count=2, favorite=true)
Person(name=p5, count=3, favorite=true)
Person(name=p3, count=0, favorite=true)
Person(name=p4, count=1, favorite=false)
Person(name=p2, count=0, favorite=false)

注意最后的count == 0条件是多余的(假设 count 不能是 < 0 )

或按 count 排序直接,最后反转一次;这将排序 p5之前p1在示例中:

persons.stream().sorted(Comparator
.comparing(Person::isFavorite)
.thenComparing(Person::getCount).reversed())
.forEach(System.out::println);

关于java - 使用1.8 jdk按多个字段对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com