我的实体类中,需要排序的字段是用String类型就行存储的,但实际存储的都是数值
List<ShopActiveRule> shopActiveRules = shopActiveRuleList.stream().sorted(Comparator.comparing(ShopActiveRule::getFavourableCondition).collect(Collectors.toList());
然后排序之后发现,9.9会被排在19.9之后,于是查看源码
发现String类型是根据字符来进行排序的,所以会出现上述问题,对排序进行修改之后代码如下
List<ShopActiveRule> shopActiveRules = shopActiveRuleList.stream().sorted(Comparator.comparing(ShopActiveRule::getFavourableCondition, Comparator.comparingDouble(Double::parseDouble))).collect(Collectors.toList());
可以正常得到想要的结果。
这个问题类似于数据库中字符串的排序,数据库中可在字段后面+0实现正常排序效果。