工作中常常有对集合中元素按要求排序的场景,整理一下自己用的排序方法
原理:java中的基本类型包装类如Integer,Double等;还有字符串String 日期Date都实现了Compareable接口,这意味着我们可以使用compareTo方法对比判断其大小
数字类型就是比较大小,提一下字符串的比较规则,如果这个字符串是等参数字符串那么返回值0,如果这个字符串是按字典顺序小于字符串参数那么返回小于0的值,如果此字符串是按字典顺序大于字符串参数那么一个大于0的值
1 List中元素为非自定义类型
List属于Collection集合子接口,我们可以借助Collection.sort()方式实现对list中元素的排序
由于字符串的对比规则,我们也可以直接对日期字符串排序,若是普通字符串,"AB" > "AA"
List<JourneyEntity> journeyEntityList = new ArrayList<>();
JourneyEntity journeyEntity = new JourneyEntity();
JourneyEntity journeyEntity1 = new JourneyEntity();
JourneyEntity journeyEntity2 = new JourneyEntity();
journeyEntity.setBeginTime("2021-9-22 12:22:33");
journeyEntity1.setBeginTime("2021-9-21 12:22:33");
journeyEntity2.setBeginTime("2019-9-25 12:22:33");
journeyEntityList.add(journeyEntity);
journeyEntityList.add(journeyEntity1);
journeyEntityList.add(journeyEntity2);
journeyEntityList.sort(Comparator.comparing(JourneyEntity::getBeginTime));
System.out.println(JSON.toJSONString(journeyEntityList));
输出:
[{"beginTime":"2019-9-25 12:22:33"},
{"beginTime":"2021-9-21 12:22:33"},
{"beginTime":"2021-9-22 12:22:33"}]
2 List中元素为自定义类型
我List中存的是Object类型(示例代码中的是JSONObject),想要根据其中某个属性排序
同理,换成其它的自定义类,也可以使用这种方法,取得其中某种属性按照我们的自定义规则排序
还有一种自定义类实现Compareable接口的写法,感觉不方便,就不写了
private static void ListSort(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
try {
LocalDateTime dt1 = LocalDateTime.parse(((JSONObject) o1).getString("endTime"), format);
LocalDateTime dt2 = LocalDateTime.parse(((JSONObject) o2).getString("endTime"), format);
if (dt1.isAfter(dt2)) {
return 1;
} else if (dt1.isBefore(dt2)) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
}
//订单根据结束时间排序
ListSort(trainOrders);