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

后端 未结 7 1666
猫巷女王i
猫巷女王i 2020-12-01 00:20

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 t

7条回答
  •  不思量自难忘°
    2020-12-01 01:24

    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);
    

提交回复
热议问题