JAVA8 Stream之Sort排序comparing 和thenComparing

今天在使用Stream排序的时候,出现了一个bug,简单的记录下,方便下次查找

首先根据降序的sort方法,对list集合中的对象的某个属性进行排序.float getFollowDegree()的返回值时,所以查询出来后进行排序的顺序是降序(DESC,从大到小)的,如果没有reversed()方法的话,就是升序排列(ASC,从小到大).这样是没有问题的...

        //对listResult进行排序,根据伴随度进行降序F
        List<FollowIMSI> collect = listResult.stream()
            .sorted(Comparator.comparing(FollowIMSI::getFollowDegree).reversed())
            .collect(Collectors.toList());

下面问题出现了.如果我想先对followDegree降序,如果followDegree相等,再根据codeDaysThirsty的值进行降序排列,很自然的就往后加了....

       //根据伴随度和30天出现比率进行排序
        List<FollowIMSI> collect1 = list1.stream()
            .sorted(Comparator.comparing(FollowIMSI::getFollowDegree).reversed()
            .thenComparing(FollowIMSI::getCodeDaysThirsty).reversed())
            .collect(Collectors.toList());

很多时候,并没有那么多想当然的,从上述代码中可以看到,先对followDegree进行降序排列,再对codeDaysThirty进行降序排列,没有问题....

其实,不然

我们需要的是对followDegree的值降序,如果值相等,再对codeDaysThirty进行降序.所以说,上述代码的理解应该为:

以codeDaysThirty进行降序排列,如果codeDaysThirty相等,再以followDegree进行排序.

所以争取的代码应该是:

       //根据伴随度和30天出现比率进行排序
        List<FollowIMSI> collect1 = list1.stream()
            .sorted(Comparator.comparing(FollowIMSI::getFollowDegree)
            .thenComparing(FollowIMSI::getCodeDaysThirsty).reversed())
            .collect(Collectors.toList());

注意在getFollowDegree()后是没有reversed()的....

所以.静下心来,你会理解其中的奥秘,从左往右进行运算的

猜你喜欢

转载自blog.csdn.net/YoungLee16/article/details/83547713