java8 stream 融汇实战
Posted 雪洗中关村
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java8 stream 融汇实战相关的知识,希望对你有一定的参考价值。
//https://segmentfault.com/q/1010000019798265 java 利用lambda 将两个list<map<String,object>>按照两个list中map的一列值合并 public static List<Map<String, Object>> merge(List<Map<String, Object>> list1, List<Map<String, Object>> list2) { list1.addAll(list2); Set<String> set_mark = new HashSet<>(); Map<Object, List<Map<String, Object>>> step1_map1 = list1.stream() .collect(Collectors.groupingBy(temp1 -> { set_mark.addAll(temp1.keySet());//暂存所有key //按 a_id 分组 return temp1.get("a_id"); //根据 a_id 牵头 生成新的 Map<Object, List<Map<String, Object>>> })); List<Map<String, Object>> res = step1_map1.entrySet().stream().map(mix -> { //合并 Stream<Map.Entry<String, Object>> step2_entryStream = //获取 entrySet().stream() mix.getValue().stream().flatMap(m -> { return m.entrySet().stream(); }); Map<String, Object> step3_map = step2_entryStream //将要return回去的 Map<String, Object> .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b)); //为没有的key赋值0 set_mark.stream().forEach(k -> { if (!step3_map.containsKey(k)) { step3_map.put(k, 0); } }); return step3_map; }).collect(Collectors.toList()); return res; }
Map<String, Object> map1 = new HashMap<>(); map1.put("a_id", 1); map1.put("in_num", 10); Map<String, Object> map2 = new HashMap<>(); map2.put("a_id", 3); map2.put("in_num", 10); List<Map<String, Object>> list1 = new ArrayList<>(); list1.add(map1); list1.add(map2); Map<String, Object> map4 = new HashMap<>(); map4.put("a_id", 1); map4.put("out_num", 20); Map<String, Object> map5 = new HashMap<>(); map5.put("a_id", 2); map5.put("out_num", 20); List<Map<String, Object>> list2 = new ArrayList<>(); list2.add(map4); list2.add(map5); List<Map<String, Object>> merge = merge(list1, list2); System.out.println(merge); //[{a_id=1, in_num=10, out_num=20}, {a_id=2, in_num=0, out_num=20}, {a_id=3, in_num=10, out_num=0}]
以上是关于java8 stream 融汇实战的主要内容,如果未能解决你的问题,请参考以下文章