网站开发与管理大作业,123网址之家,网站推广的途径和方法,广东省新闻使用steam().sorted(Comparator.comparing())对ListT集合里的String类型字段进行倒序排序#xff0c;发现倒序失效。记录解决方案。
异常代码如下: customerVOList customerVOList.stream().sorted(Comparator.comparing(CustomerVOVO::getCustomerRate).reversed()…使用steam().sorted(Comparator.comparing())对ListT集合里的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类型字段进行自定义规则排序可能会出现未知问题。