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<ResponseData> result = new ArrayList<>();
...........................

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值