Merge Map Java 8 Stream

前端 未结 4 728
灰色年华
灰色年华 2020-12-28 17:56

I would like to merge two Map with JAVA 8 Stream:

Map> mapGlobal = new HashMap>();
Map

        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 18:27

    Using foreach over Map can be used to merge given arraylist.

        public Map> merge(Map> map1, Map> map2) {
        Map> map = new HashMap<>();
        map.putAll(map1);
    
        map2.forEach((key , value) -> {
            //Get the value for key in map.
            ArrayList list = map.get(key);
            if (list == null) {
                map.put(key,value);
            }
            else {
                //Merge two list together
                ArrayList mergedValue = new ArrayList<>(value);
                mergedValue.addAll(list);
                map.put(key , mergedValue);
            }
        });
        return map;
    }
    

提交回复
热议问题