JAVA合并两个具有相同key的map为list

2020-04-26 10:13:54 浏览数 (1)

JAVA合并两个具有相同key的map为list,不多说,直接上代码:

代码语言:javascript复制
public class MapUtil {

    public static void  main(String[] args){
        List<Map<String,String>> osvList = new ArrayList<>();
        Map<String,String> map1 = new HashMap<>();
        map1.put("osV","5.1");
        map1.put("gaidNum","100");
        Map<String,String> map2 = new HashMap<>();
        map2.put("osV","4.4.2");
        map2.put("gaidNum","150");
        osvList.add(map1);
        osvList.add(map2);
        List<Map<String,String>> ipList = new ArrayList<>();
        Map<String,String> map3 = new HashMap<>();
        map3.put("osV","5.1");
        map3.put("ipNum","200");
        Map<String,String> map4 = new HashMap<>();
        map4.put("osV","4.4.2");
        map4.put("ipNum","300");
        ipList.add(map3);
        ipList.add(map4);
        List<Map<String,String>> mapsList = new ArrayList<>();
        mapsList.add(map1);
        mapsList.add(map3);
        System.out.println("mapsList=" mapsList);
        List<Map<String,String>> megeList = merge(mapsList,"osV");
        System.out.println("megeList=" megeList);
    }

    /**
     * 合并两个具有相同key的map为list
     * @param m1 要合并的list
     * @param mergeKey 以哪个key为基准合并
     * @return
     */
    public static List<Map<String, String>> merge(List<Map<String, String>> m1, String mergeKey){
        Set<String> set = new HashSet<>();
        return m1.stream()
                .filter(map->map.get(mergeKey)!=null)
                .collect(Collectors.groupingBy(o->{
                    set.addAll(o.keySet());//暂存所有key
                    return o.get(mergeKey).toString(); //按mergeKey分组
                }))
                .entrySet().stream().map(o->{
                    Map<String, String> map = o.getValue().stream().flatMap(m->{ //合并
                        return m.entrySet().stream();
                    }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,b)->b));
                    set.stream().forEach(k->{//为没有的key赋值0
                        if(!map.containsKey(k)) map.put(k, "0");
                    });
                    return map;
                }).collect(Collectors.toList());
    }

}

0 人点赞