gpt4 book ai didi

java - 如何使用 partitioningBy,然后使用 Java Streams 分别对结果列表进行排序

转载 作者:行者123 更新时间:2023-12-02 15:50:47 24 4
gpt4 key购买 nike

我有一个像下面这样的对象:

public class Resource {
int level;
String identifier;
boolean isEducational;

public Resource(String level, String identifier, boolean isEducational) {
this.level = level;
this.identifier = identifier;
this.isEducational = isEducational;
}

// getter and setters
}

以及这些资源的列表,例如:

List<Resource> resources = Arrays.asList(new Resource(4, "a", true ),
new Resource(4, "b", false),
new Resource(3, "c", true ),
new Resource(3, "d", false ),
new Resource(2, "e", true ),
new Resource(2, "f" , false));

我想按它们的 level 属性对这个列表进行排序,但是这种排序应该分别针对 isEducational 资源和 non- 进行是教育资源。

因此,经过排序后,结果列表应按以下顺序排列:

[Resource e, Resource c, Resource a, Resource f, Resource d, Resource b]

// basically, isEducational sorted first, followed by non-educational resources

所以我尝试了以下操作:

List<Resource> resources1 = resources.stream()
.collect(partitioningBy(r -> r.isEducational()))
.values()
.stream()
.map(list -> {
return list
.stream()
.sorted(comparing(r -> r.getLevel()))
.collect(toList());
})
.flatMap(Collection::stream)
.collect(toList());


resources1.stream().forEach(System.out::println);

并将输出打印为:

Resource{level='2', identifier='f', isEducational='false'}
Resource{level='3', identifier='d', isEducational='false'}
Resource{level='4', identifier='b', isEducational='false'}
Resource{level='2', identifier='e', isEducational='true'}
Resource{level='3', identifier='c', isEducational='true'}
Resource{level='4', identifier='a', isEducational='true'}

这与我想要的相反,即首先打印非教育资源,然后是教育资源

有没有更好的方法来实现这个?我不想再次迭代列表来重新排列它。谢谢。

最佳答案

根本不需要使用 partitioningBy。您只需要两个比较器首先通过 isEducational 进行比较,然后通过 level 进行比较,您可以使用 Comparator.thenComparing

将其链接起来
resources.stream()
.sorted(Comparator.comparing(Resource::isEducational).reversed().thenComparing(Resource::getLevel))
.forEach(System.out::println);

您可以为比较器引入变量以使您的代码更具可读性,或者如果您想以灵活的方式重用它们:

Comparator<Resource> byIsEdu = Comparator.comparing(Resource::isEducational).reversed();
Comparator<Resource> byLevel = Comparator.comparing(Resource::getLevel);

resources.stream()
.sorted(byIsEdu.thenComparing(byLevel))
.forEach(System.out::println);

关于java - 如何使用 partitioningBy,然后使用 Java Streams 分别对结果列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72572954/

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