Java之List.steam().sorted(Comparator.comparing())排序异常解决方案
创始人
2025-01-09 21:07:12
0

使用steam().sorted(Comparator.comparing())对List集合里的String类型字段进行倒序排序,发现倒序失效。记录解决方案。

异常代码如下:

 customerVOList = customerVOList.stream()                 .sorted(Comparator.comparing(CustomerVOVO::getCustomerRate).reversed())                 .collect(Collectors.toList());

getCustomerRate 是String类型的,存的是double类型的值,要根据这个字段倒序返回,发现这种方法排序是乱的。

解决方案一

        // 把String类型字段转换成Double类型进行自然升序排序 customerVOList = customerVOList.stream()                                 .sorted(Comparator.comparingDouble(v -> Double.valueOf(v.getCustomerRate())))                                 .collect(Collectors.toList());         // 先自然排序然后再倒序         Collections.reverse(customerLoanMapVOList);

这种方案需要先把String类型转换成Double类型自然升序排序后再使用Collections对集合进行倒序,reversed()用不了,用了就报错 "Cannot resolve method 'getCustomerRate' in 'Object'"。

解决方案二

        customerVOList = customerVOList.stream()                                 .sorted((v1,v2) -> Double.valueOf(v2.getCustomerRate()).compareTo(Double.valueOf(v1.getCustomerRate())))                                 .collect(Collectors.toList());

直接不要Comparator,一段代码搞定。

延伸

使用steam().sorted(Comparator.comparing())对自定义对象集合中的字段进行排序,避免直接对String类型字段进行自定义规则排序,可能会出现未知问题。

相关内容

热门资讯

2分钟德州透视挂!hhpoke... 2分钟德州透视挂!hhpoker开挂教程,德州透视插件,详细教程(有挂功能)1、完成德州透视插件透视...
九分钟开辅助!wepoker辅... 九分钟开辅助!wepoker辅助软件价格(透视底牌)详细辅助程序(本来是真的有挂)1、任何wepok...
9分钟透视插件!hh poke... 9分钟透视插件!hh poker软件,hhpoker是正品吗,详细教程(有挂智能)1、hh poke...
7分钟插件辅助!wepoker... 7分钟插件辅助!wepoker买钻石有用吗(透视底牌)详细辅助插件(果然是有挂)7分钟插件辅助!we...
八分钟作弊实战!hhpoker... 八分钟作弊实战!hhpoker脚本,hhpoker辅助靠谱吗,详细教程(有挂安装)1、完成hhpok...
二分钟苹果版!wepoker有... 二分钟苹果版!wepoker有辅助器吗(透视底牌)详细辅助免费(切实真的是有挂)1、点击下载安装,插...
八分钟破解工具!德州透视hhp... 八分钟破解工具!德州透视hhpoker,hh poker辅助器先试用,详细教程(有挂插件)1、该软件...
二分钟作弊!wepoker私人... 二分钟作弊!wepoker私人局可以透视(透视底牌)详细辅助作弊器(本来真的有挂);暗藏猫腻,小编详...
五分钟外挂!德扑HHpoker... 五分钟外挂!德扑HHpoker有挂吗(透视脚本)详细辅助助手(确实真的是有挂)1、任何ai辅助神器的...
5分钟新号!wepoker透视... 5分钟新号!wepoker透视器免费(透视底牌)详细辅助外挂(确实是真的有挂)1、打开软件启动之后找...