哈希Map合并工具类在Java是什么样的

langrisser
发布于 2020-8-31 19:43
1.6w浏览
0收藏

有两个哈希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;
	}
	
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.

Console打印:

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

 

分类
已于2020-9-2 18:09:58修改
收藏
回复
举报


回复
    相关推荐