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

后端 未结 7 1661
猫巷女王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:15

    With Java 8 there is this API method to accomplish your requirement.

    map.putIfAbsent(key, value)
    

    If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

提交回复
热议问题