java - 意外的排序列表
问题描述
问候,
我有 2 个对象:
- 请愿
- 签字人(签字人)
我写了这段代码:
public List<Petition> getTheMostSigned(long groupId){
List<Petition> petitionList = petitionPersistence.findByStatusAndGroupId(0,groupId);
_log.info("list avant getTheMostSigned size : "+petitionList.stream().map(petition -> petition.getSignataires().size()).collect(Collectors.toList()));
List<Petition> resultList = petitionList.stream()
.sorted(Comparator.comparingInt(petition -> petition.getSignataires().size()))
.sorted(Collections.reverseOrder())
.collect(Collectors.toList());
_log.info("list apres getTheMostSigned size : "+resultList.stream().map(petition -> petition.getSignataires().size()).collect(Collectors.toList()));
return resultList;
getSignataires() 返回一个列表。
但结果不是我所期望的:
2018-09-12 12:44:25.686 INFO [http-nio-8080-exec-10][PetitionLocalServiceImpl:390] list avant getTheMostSigned size : [0, 0, 400, 0, 3, 401, 5501]
2018-09-12 12:44:25.856 INFO [http-nio-8080-exec-10][PetitionLocalServiceImpl:396] list apres getTheMostSigned size : [5501, 401, 3, 0, 0, **400**, 0]
正如你所看到的,倒数第二不是好的。你知道为什么比较器不做这项工作吗?
解决方案
当您链接两种类型时,结果是预期的。
第一个 ( .sorted(Comparator.comparingInt(petition -> petition.getSignataires().size())
) 按列表字段大小排序)。然后第二个 ( .sorted(Collections.reverseOrder())
) 覆盖第一个排序结果,因为最后一个根据 的反向自然顺序进行排序Petition
。
当您调用两次排序流操作时,大致上就像您使用了这个逻辑:
List<Petition> petitionList = ...;
// first sort
petitionList.sort(Comparator.comparingInt(petition -> petition.getSignataires().size());
// second sort
petitionList.sort(Collections.reversed());
您需要定义一个Comparator
结合这些约束的实例。
从 Java 8 开始,您可以创建Comparator
s 并将它们组合起来,这主要归功于.thenComparingXXX()
和.reversed()
方法。
所以你可以这样做:
.sorted(Comparator.comparingInt(petition -> petition.getSignataires().size())
.reversed()
)
推荐阅读
- opencv - sklearn/opencv 库中的 PCA 转换/项目函数是否保留原始数据集的顺序?
- java - 按日期排序对象列表并应用过滤器
- django - 如何在表单集中显示/隐藏表单中的选定字段?
- gps - 根据预定间隔在两个 GPS 点之间插入附加点
- maven - 过滤发布到 Artifactory 的工件
- servicestack - 为什么服务堆栈返回 Int64 而不是 Int32?
- c - 有人能解释一下在这段代码中找到全部部分有什么问题吗
- r - Aref(来自匈牙利 babel)在 bookdown
- python - 存储大型推文数据集:文本文件与数据库
- sql - SQL:在 SQL 中结合 LIKE 和 IN,并在一列中显示 LIKE 的数组