当前位置: 首页 > news >正文

Java之List.steam().sorted(Comparator.comparing())排序异常解决方案

使用steam().sorted(Comparator.comparing())对List<T>集合里的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类型字段进行自定义规则排序,可能会出现未知问题。

http://www.lryc.cn/news/320613.html

相关文章:

  • js判断对象是否有某个属性
  • CleanMyMac X2024永久免费的强大的Mac清理工具
  • 等保测评的知识
  • 【算法】多路归并(鱼塘钓鱼)
  • unity3d Animal Controller的Animal组件中General基础部分理解
  • css背景从上到下颜色渐变、css背景从左到右颜色渐变、 css框线展示外阴影、css框线展示内阴影
  • Nacos学习笔记
  • 微信小程序 nodejs+vue+uninapp学生在线选课作业管理系统
  • trpc-go 博客系统
  • 【JAVA】Servlet开发
  • k8s helm 删除 tiller
  • Python入门(小白友好)
  • 【数据结构与算法】:非递归实现快速排序、归并排序
  • 2024-3-18-C++day6作业
  • 【OceanBase诊断调优】—— 敏捷诊断工具obdiag一键分析OB集群日志设计与实践
  • python 调用redis创建查询key
  • 归并排序思路
  • 【蓝桥杯选拔赛真题65】python输出三个字符 第十五届青少年组蓝桥杯python选拔赛真题 算法思维真题解析
  • K8S日志收集方案-EFK部署
  • js基础语法大全(时间戳,uuid,字符串转json)
  • uView LoadingIcon 加载动画
  • Elasticsearch使用Kibana进行基础操作
  • “SRP模型+”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展应用教程
  • 【Windows 常用工具系列 15 -- VMWARE ubuntu 安装教程】
  • SpringSecurity(SpringBoot2.X版本实现)
  • 仿牛客项目Day8:社区核心功能2
  • Vmware虚拟机配置虚拟网卡
  • 双向链表代码(带哨兵位循环/不带哨兵位不循环
  • C语言自学笔记13----C语言指针与函数
  • 每日五道java面试题之mybatis篇(一)