方法1:
List<RainConditionDetailInfoDto> detailInfoList = new ArrayList<>(); //将数据按字段正序排序 detailInfoList.sort(Comparator.comparing(RainConditionDetailInfoDto::getDayDrp)); //将数据按字段正序排序(注意字段为null时) List<User> nullsLastCollect = userList.stream().sorted(Comparator.comparing(User::getName, Comparator.nullsLast(String::compareTo))) .collect(Collectors.toList()); //将数据按字段倒序排序 detailInfoList.sort(Comparator.comparing(RainConditionDetailInfoDto::getDayDrp).reversed());方法2:
List<RainConditionDetailInfoDto> detailInfoList = new ArrayList<>();
//将数据按照字段正序排序
Collections.sort(detailInfoList , new Comparator<RainConditionDetailInfoDto>() { @Override public int compare(RainConditionDetailInfoDto o1, RainConditionDetailInfoDto o2) { // 按照正序排列(注意数据为null) if(null!=o1.getDrp() && null!=o2.getDrp()){ return o1.getDrp().compareTo(o2.getDrp()); }else{ return 1 }
} });
//将数据按照字段倒序排序
Collections.sort(detailInfoList , new Comparator<RainConditionDetailInfoDto>() { @Override public int compare(RainConditionDetailInfoDto o1, RainConditionDetailInfoDto o2) { // 按照降序排列(注意数据为null) if(null!=o2.getDrp() && null!=o1.getDrp()){ return o2.getDrp().compareTo(o1.getDrp()); }else{ return 1 }
} });
方法3:
//按照字段进行排序(字段为null时也参与排序)
List<User> nullsLastCollect = userList.stream() .sorted(Comparator.comparing(User::getName, Comparator.nullsLast(String::compareTo))) .collect(Collectors.toList());
//对多个字段进行排序
list.sort(Comparator.comparing(Employee::getAge, Comparator.nullsLast(Integer::compareTo)).thenComparing(Employee::getId, Comparator.nullsFirst(Integer::compareTo)));