首页 > 解决方案 > 意外的排序列表

问题描述

问候,

我有 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]

正如你所看到的,倒数第二不是好的。你知道为什么比较器不做这项工作吗?

标签: javalistlambdacomparator

解决方案


当您链接两种类型时,结果是预期的。
第一个 ( .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 开始,您可以创建Comparators 并将它们组合起来,这主要归功于.thenComparingXXX().reversed()方法。

所以你可以这样做:

.sorted(Comparator.comparingInt(petition -> petition.getSignataires().size())
                  .reversed()
       )

推荐阅读