一般列表排序
List
List<Float> floatList = new ArrayList<>();
floatList.add(10.21f);
floatList.add(15.245f);
floatList.add(5.75f);
floatList.add(1.21f);
floatList.add(0.68f);
floatList.add(-0.54f);
floatList.add(-5.86f);
floatList.add(-10.54f);
// 执行过后列表内部已经排序完成
floatList.sort(Comparator.comparing(Float::floatValue));
// 执行过后列表内部已经排序完成
Collections.reverse(floatList);
System.out.println("floatList = " + floatList);
Stream 方式
List<Float> floatList = new ArrayList<>();
floatList.add(10.21f);
floatList.add(15.245f);
floatList.add(5.75f);
floatList.add(1.21f);
floatList.add(0.68f);
floatList.add(-0.54f);
floatList.add(-5.86f);
floatList.add(-10.54f);
// 需要重新获取结果
List<Float> collect = floatList.stream().sorted().collect(Collectors.toList());
System.out.println("floatList = " + collect);
其他类型类似如此做法
Date 也支持此类排序
List<Date> dateList = new ArrayList<>();
dateList.add(new Date());
dateList.add(new Date());
dateList.add(new Date(1775743650638L));
dateList.add(new Date());
dateList.add(new Date());
dateList.add(new Date()); // 为 null 会报错
// Comparator.reverseOrder() 代表反转顺序 默认升序,这里要倒叙
List<Date> collect = dateList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println("JSONObject.toJSONString(collect) = " + JSONObject.toJSONString(collect));
对自定义类某一属性或多个属性排序
Stream
List<PersonVO> list = new ArrayList<>();
PersonVO personVO = new PersonVO();
personVO.setPId(1L);
personVO.setAge(4);
list.add(personVO);
PersonVO personVO1 = new PersonVO();
personVO1.setPId(1L);
personVO1.setAge(3);
list.add(personVO1);
PersonVO personVO2 = new PersonVO();
personVO2.setPId(2L);
personVO2.setAge(6);
list.add(personVO2);
PersonVO personVO3 = new PersonVO();
personVO3.setPId(4L);
personVO3.setAge(7);
list.add(personVO3);
PersonVO personVO4 = new PersonVO();
personVO4.setPId(0L);
personVO4.setAge(6);
list.add(personVO4);
// 按照Pid 排序 默认升序
List<PersonVO> collect = list.stream().sorted(Comparator.comparing(PersonVO::getPId)).collect(Collectors.toList());
// reversed 反转后为降序
List<PersonVO> collect1 = list.stream().sorted(Comparator.comparing(PersonVO::getPId).reversed()).collect(Collectors.toList());
// 先按照pid 排序,相同情况下使用 age 排序 默认升序
List<PersonVO> collect2 = list.stream().sorted(Comparator.comparing(PersonVO::getPId).thenComparing(PersonVO::getAge)).collect(Collectors.toList());
// 先按照pid 排序,相同情况下使用 age 排序 最后全部采用降序
List<PersonVO> collect3 = list.stream().sorted(Comparator.comparing(PersonVO::getPId).thenComparing(PersonVO::getAge).reversed()).collect(Collectors.toList());
// 先按照pid 排序,相同情况下使用 age 排序 pid 降序, age 升序
List<PersonVO> collect4 = list.stream().sorted(Comparator.comparing(PersonVO::getPId).reversed().thenComparing(PersonVO::getAge)).collect(Collectors.toList());
// 先按照pid 排序,相同情况下使用 age 排序,Pid 升序,age 降序 可以看做 负负得正,前面反转后后面再次反转会将前面的反转抵消
List<PersonVO> collect5 = list.stream().sorted(Comparator.comparing(PersonVO::getPId).reversed().thenComparing(PersonVO::getAge).reversed()).collect(Collectors.toList());