java对List<Student>或者List<Map>进行排序
对List(Map)进行排序
public void sortLastOnlineList(CloudRInfoPo cloudRInfoPo, List<Map<String, Object>> result) {
if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "desc".equals(cloudRInfoPo.getSort())) {
//正序
result.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("lastOnlineTime"))));
}
if (!StringUtils.isEmpty(cloudRInfoPo.getDuration()) || "asc".equals(cloudRInfoPo.getSort())) {
//倒序
result.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("lastOnlineTime"))).reversed());
}
}
对List进行排序
List<Student> students = new ArrayList<>();
Student student1 = new Student("六年级","Math","小张",1D);
students.add(student1);
Student student2 = new Student("三年级上","English","小钱",8D);
students.add(student2);
Student student3 = new Student("五年级","Chinese","小孙",6D);
students.add(student3);
倒序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getMark).reversed()).collect(Collectors.toList());
控制台:
排序前:1.0|8.0|6.0|
排序后:8.0|6.0|1.0|
正序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getMark)).collect(Collectors.toList());
控制台:
排序前:1.0|8.0|6.0|
排序后:1.0|6.0|8.0|
需要注意的是:
排序字段为null时会报错!!!
需要对null值进行处理或过滤掉
还没有评论,来说两句吧...