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

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

    Just iterate and add:

    for(Map.Entry e : a.entrySet())
      if(!b.containsKey(e.getKey())
        b.put(e.getKey(), e.getValue());
    

    Edit to add:

    If you can make changes to a, you can also do:

    a.putAll(b)
    

    and a will have exactly what you need. (all the entries in b and all the entries in a that aren't in b)

提交回复
热议问题