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类型字段进行自定义规则排序,可能会出现未知问题。

相关内容

热门资讯

透视规律!wepoker透视脚... 透视规律!wepoker透视脚本,总是真的是有挂(透视)揭秘教程(有挂揭秘);1、金币登录送、破产送...
透视app!aapoker插件... 透视app!aapoker插件(透视)透视脚本入口(原来真的有挂);1、首先打开aapoker插件最...
透视苹果版"aapo... 透视苹果版"aapoker如何设置胜率"确实真的有挂(透视)教你教程(有挂细节)1、全新机制【aap...
透视数据!wepoker可以开... 透视数据!wepoker可以开透视吗,原本存在有挂(透视)辅助教程(有挂详情);1、在wepoker...
透视软件!aapoker透视脚... 透视软件!aapoker透视脚本下载(透视)ai插件(确实是有挂)aapoker透视脚本下载辅助器中...
透视好友房"hhpo... 透视好友房"hhpoker作弊码"切实是有挂(透视)插件教程(有挂揭秘)1)hhpoker作弊码辅助...
透视辅助!wepoker插件辅... 透视辅助!wepoker插件辅助,本然是有挂(透视)可靠教程(有挂教程);1、下载好wepoker插...
透视透视挂!aapoker怎么... 透视透视挂!aapoker怎么设置提高好牌几率(透视)透视插件(本来是有挂);该软件可以轻松地帮助玩...
透视实锤"hhpok... 透视实锤"hhpoker有后台操作吗"好像真的是有挂(透视)可靠教程(有挂工具)1、hhpoker有...
透视规律!德普之星有透视辅助吗... 透视规律!德普之星有透视辅助吗,原先存在有挂(透视)安装教程(有挂脚本)进入游戏-大厅左侧-新手福利...