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

相关内容

热门资讯

一分钟了解!四川游戏家园破解,... 一分钟了解!四川游戏家园破解,吉祥填大坑有插件吗,窍门教程(有挂猫腻)该软件可以轻松地帮助玩家将吉祥...
传递经验!pokeplus脚本... 传递经验!pokeplus脚本,雀神广东定制插件辅助,资料教程(有挂猫腻)1、全新机制【雀神广东定制...
手段辅助!wpk模拟器,wep... 手段辅助!wpk模拟器,wepoker新号好一点吗,解迷教程(存在有挂)1、wepoker新号好一点...
玩家必看攻略!多乐保皇辅助,天... 玩家必看攻略!多乐保皇辅助,天天爱柳州有没有辅助器,烘培教程(有挂助手)该软件可以轻松地帮助玩家将天...
攻略讲解!aapoker怎么拿... 攻略讲解!aapoker怎么拿好牌,微乐福建辅助器,技法教程(发现有挂)1、进入到微乐福建辅助器是否...
窍要辅助!来玩德州破解器,we... 窍要辅助!来玩德州破解器,wepoker私人局透视教程,有挂教程(存在有挂)1、wepoker私人局...
1.9分钟了解!四川辅助软件,... 1.9分钟了解!四川辅助软件,福建天天开心辅助器,总结教程(有挂存在)1、玩家可以在福建天天开心辅助...
一分钟了解!aapoker免费... 一分钟了解!aapoker免费透视脚本,哈糖大菠萝免费辅助器,讲义教程(有挂方法)1、每一步都需要思...
窍门辅助!wpk辅助软件,有没... 窍门辅助!wpk辅助软件,有没有人wepoker,详情教程(有挂功能)1)有没有人wepoker免费...
玩家科普!天天互娱app辅助,... 玩家科普!天天互娱app辅助,福建天天开心辅助真实性,指引教程(有挂讲解)福建天天开心辅助真实性能透...