意外的排序列表

Ale*_*ERE 3 java lambda list comparator

问候,

我有2个对象:

  • 请愿
  • Signataire(签字)

我写了这段代码:

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;
Run Code Online (Sandbox Code Playgroud)

getSignataires()返回一个List.

但结果不是我的预期:

在此输入图像描述

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]
Run Code Online (Sandbox Code Playgroud)

如你所见,倒数第二个不是好的.你知道为什么比较者没有做这个工作吗?

dav*_*xxx 5

当您链接两种时,结果是预期的.
第一个(.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());
Run Code Online (Sandbox Code Playgroud)

您需要的是定义Comparator组合这些约束的实例.
从Java 8开始,您可以创建Comparator并组合它们,这主要归功于.thenComparingXXX().reversed()方法.

所以你可以这样做:

.sorted(Comparator.comparingInt(petition -> petition.getSignataires().size())
                  .reversed()
       )
Run Code Online (Sandbox Code Playgroud)