哈希Map合并工具类

有两个哈希Map,如果要实现Map追加的话,可以使用putAll()方法,不可以使用put()方法,但是如果出现两个Map有相同的key,但是值不同,这种情况就可以使用这个工具类进行集合合并



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CombineMapUtil {

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<String,Object>(); 
        map.put("test1", "1");
        map.put("test2", "2");
        map.put("test3", "3");

        Map<String,Object> plus = new HashMap<String,Object>();
        plus.put("test1", "2");
        plus.put("plus2", "2");
        plus.put("plus3", "3");

        Map<String,Map<String,Object>> testmap = new HashMap<>();

        List<Map> list = new ArrayList<Map>();

        list.add(map);
        list.add(plus);

        System.out.println(combineMap(list));

    }

    public static Map<String,List> combineMap(List<Map> list) {
        Map<String,List> map = new HashMap<>();
        for(Map m:list){
            Iterator<String> iter= m.keySet().iterator();
            while(iter.hasNext()){
                String key = iter.next();
                if(!map.containsKey(key)){
                    List tmpList = new ArrayList<>();
                    tmpList.add(m.get(key));
                    map.put(key, tmpList);
                }else{
                    map.get(key).add(m.get(key));  
                }
            }
        }
        return map;
    }

}

Console打印:

{test1=[1, 2], plus3=[3], plus2=[2], test2=[2], test3=[3]}

猜你喜欢

转载自blog.csdn.net/u014427391/article/details/79716986
今日推荐