Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values.

Whats the best way to do that?

I was thinking instead iterating the keySet and checkig if it exist or not, I would

Map temp = new HashMap(); // generic later temp.putAll(Amap); A.clear(); A.putAll(Bmap); A.putAll(temp); 
like image 205
rapadura Avatar asked Aug 25 '11 17:08

rapadura


People also ask

Can two keys have same value in HashMap?

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key. For example: For Key A, you want to store - Apple, Aeroplane.

What happen if we add same key with different values to HashMap?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

What happens when you put a key object in a HashMap that is already present?

What happens if we put a key object in a HashMap which exists? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.


1 Answers

It looks like you are willing to create a temporary Map, so I'd do it like this:

Map tmp = new HashMap(patch); tmp.keySet().removeAll(target.keySet()); target.putAll(tmp); 

Here, patch is the map that you are adding to the target map.

Thanks to Louis Wasserman, here's a version that takes advantage of the new methods in Java 8:

patch.forEach(target::putIfAbsent); 
like image 74
erickson Avatar answered Sep 30 '22 12:09

erickson