java Comparator.comparing 排序异常

发布时间 2023-06-08 16:20:44作者: 大木瓜

今天在Java中使用 Comparator.comparing方法排序时遇到一个异常,明明已经使用了Comparator.comparing从小到大排序,但是1-10以内的顺序还好,>10的时候排序就乱了

代码如下:

            List<MyRouteLongitudeAndLatitudeVo> collectVos = myRouteLongitudeAndLatitudeVos
                .stream()
                .sorted(Comparator.comparing(MyRouteLongitudeAndLatitudeVo::getDeliveryOrder))//根据序号id排序
                .collect(Collectors.toList());

尝试了半天后找到解决方法:

先将要排序的字段转化成int类型,然后再排序,不要用String类型去排序,不然就会乱掉。改进后的代码如下:

            List<MyRouteLongitudeAndLatitudeVo> collectVos = myRouteLongitudeAndLatitudeVos
                .stream()
                .sorted(Comparator.comparingInt(vo -> Integer.parseInt(vo.getDeliveryOrder())))
                .collect(Collectors.toList());

------------------问题解决 ------------------