List.stream()常用方法

list.stream().collect(Collectors.toMap(xxx)): list.stream():把list转成流,list.stream().collect():
把流转成集合,具体是map,还是list/set就看参数是Collectors.toMap还是Collectors.toList/Collectors.toSet.
流是不存储数据的,在流中处理完数据后需要把流中的数据转到新的集合中,Collectors.toMap就是最终
转到map集合中,还有toSet,toList.
场景一: 将List转成map
示例:
复制代码
List<JSONObject> candidates = projectMapper.getCandidateList();
//candidates 是从数据库里查出来结果集,包含,eventId,suppNm,rank三个字段,
现在把eventId当key,suppNm,rank转成jsonobject当value.
Map<String, List<JSONObject>> candidatesMap = candidates.stream().collect
(Collectors.toMap(w -> w.getString("eventId"), w -> { ArrayList<JSONObject> candidateList = new ArrayList<>(); JSONObject jsonObject = new JSONObject(); jsonObject.put("suppNm",w.get("suppNm")); jsonObject.put("rank",w.get("rank")); candidateList.add(jsonObject); return candidateList; },
//
指定key重复的处理方式
(List<JSONObject> oldValue,List<JSONObject> newValue)->{ oldValue.addAll(newValue); return oldValue; }));
复制代码

场景二: 对list中数据做处理后还转成list

复制代码
List<JSONObject> list = searchMapper.categorySelect();
//list是查询的结果集,包含firstCode,firstName字段
        List<JSONObject> parent_id = list.stream().map(e -> {
将list里的JSONObject类型取出来做处理,仍旧映射成JSONObject类型,也可以取出一个字段映射成string类型,map是映射的意思,
对集合内每个变量做转换,跟Java的map数据结构没关系 JSONObject jsonObject
= new JSONObject(); jsonObject.put("code",e.get("firstCode")); jsonObject.put("name",e.get("firstName")); return jsonObject; }).distinct().collect(Collectors.toList());
复制代码
distinct()是去重,还有filter()过滤,limit()限制条数,sort()排序,forEach()循环处理list每条数据 等方法.
详细使用案例文章:https://blog.csdn.net/TonyStarkF/article/details/122882539
还可以组合使用
list.stream().filter(x1 ->x1过滤条件).map(e -> {})这样符合filter过滤条件的数据才会映射
posted @   杨吃羊  阅读(7431)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示