Java stream 排序

第一种方式,直接比较

根据年龄大小来比较:
list = list.stream()
           .sorted((p1, p2) -> p1.getAge() - p2.getAge())
           .collect(Collectors.toList());

第二种方式,通过stream的接口指定排序类型操作

list = list.stream()
           .sorted(Comparator.comparingInt(Person::getAge))
           .collect(Collectors.toList());

第三种方式,通过stream的接口不指定排序类型操作,reversed:反向排序,默认正向排序

list = energyLogList.stream()
                    .sorted(Comparator.comparing(EnergyLog::getResult).reversed())
                    .collect(Collectors.toList());

第四种方式,通过stream自定义Comparator排序

List result = new ArrayList<>();
...........................

result = result.stream().sorted(new Comparator() {
            @Override
            public int compare(ResponseData o1, ResponseData o2) {
                try{
                    Date d1 = DateUtils.getDateOfPattern(o1.getDateTime(),"HH:mm:ss");
                    Date d2 = DateUtils.getDateOfPattern(o2.getDateTime(),"HH:mm:ss");
                    return d1.compareTo(d2);
                }catch (ParseException e){
                    e.printStackTrace();
                }

            return 0;
            }
        }).collect(Collectors.toList());

第五种方式,通过stream对多个属性进行排序

Map map1 = new HashMap<>();
map1.put("custId","1");
map1.put("custName","a");
Map map2 = new HashMap<>();
map2.put("custId","2");
map2.put("custName","b");
Map map3 = new HashMap<>();
map3.put("custId","3");
map3.put("custName","c");
List> rawMkInfoList = new ArrayList>();
rawList.add(map1);
rawList.add(map2);
rawList.add(map3);
List> sortedList = rawList.stream().sorted(
    Comparator.comparing(m1 -> ((Map) m1).get("custId")
    , Comparator.reverseOrder()).thenComparing(m2 -> ((Map) m2).get("custName"),
    Comparator.reverseOrder())
    ).collect(Collectors.toList()
);

你可能感兴趣的:(java,python,开发语言)