List.stream()常用方法


1 将List转成map

list.stream().collect(Collectors.toMap(xxx)): list.stream():把list转成流,list.stream().collect():把流转回list.
示例:
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; }));

2 对list<T>中的泛型数据做处理

List<JSONObject> list = searchMapper.categorySelect();
//list是查询的结果集,包含firstCode,firstName字段
        List<JSONObject> parent_id = list.stream().map(e -> {
将list里的JSONObject类型取出来做处理,仍旧映射成JSONObject类型,也可以取出一个字段映射成string类型
            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每条数据 等方法.
还可以组合使用
list.stream().filter(x1 ->x1过滤条件).map(e -> {})这样符合filter过滤条件的数据才会映射


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM