我有一個如下物件:
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資源和非isEducational資源分別進行。
因此,排序后,結果串列應按以下順序排列:
[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'}
這與我想要的相反,即首先印刷非教育,其次是教育資源
有沒有更好的方法來實作這一目標?我不想再次迭代串列來重新排列它。謝謝。
uj5u.com熱心網友回復:
完全不需要使用partitioningBy。您只需要兩個比較器首先比較 byisEducational然后 by 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/489002.html
