Stream流的常用操作

用流操作集合常用方法:

用指定字段做为分组条件:
Map<String, List<JSONObject>> inherentMap = inherentList.stream().collect(Collectors.groupingBy(o -> o.getString("ins_code")));

用指定字段分组并保持数据原有排序
LinkedHashMap<String, List<JSONObject>> dataLinkedList = list.stream().collect(Collectors.groupingBy(o -> o.getString("devCode"), LinkedHashMap::new, Collectors.toList()));

将指定字段排序
dataList.sort(Comparator.comparing(o -> o.getString("gatherTime")));
alarmRecoredList.sort(Comparator.comparing((Map<String, Object> o) -> String.valueOf(getMapValue(o, "createTime"))));
alarmRecoredList.sort(Comparator.comparing((Map<String, Object> o) -> String.valueOf(getMapValue(o, "createTime"))).reversed());

将某值映射成另一个值并求和或收集

double predictFee = yearEnergyList.stream().mapToDouble(s -> Double.parseDouble(s.getPredictFee())).sum();


将值映射去重并收集
List<String> propTypeList = jsonObjectList.stream().map(e -> e.getString("propType")).distinct().collect(Collectors.toList());

对集合进行过滤并对指定字段值进行排序,收集结果值
List<JSONObject> collect = lst.stream().filter(o -> o.getString("propCode").equals(propCode)).sorted(Comparator.comparing(ob -> ob.getString("createTime"))).collect(Collectors.toList());

将集合元素取出装入map

Map<Integer, String> result3 = list.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getName()));
        
Map<String, Long> result1 = list.stream().collect(Collectors.toMap(Hosting::getName, Hosting::getWebsites));

先排序再收集
Map<String, Long> result = list.stream().sorted(Comparator.comparingLong(Hosting::getWebsites).reversed())
        .collect(Collectors.toMap(Hosting::getName,Hosting::getWebsites,(oldValue, newValue) -> oldValue,
            LinkedHashMap::new));

将对象中某字段作为key,整体作为value
 Map<String, JSONObject> dataMap = energyDosageMonthBySysIns.stream()
                                .filter(o -> StringUtils.isNotBlank(o.getString("deviceId")))
                                .collect(Collectors.toMap(item -> item.getString("deviceId"), Function.identity()));        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值