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

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

    Using Guava's Maps class' utility methods to compute the difference of 2 maps you can do it in a single line, with a method signature which makes it more clear what you are trying to accomplish:

    public static void main(final String[] args) {
        // Create some maps
        final Map map1 = new HashMap();
        map1.put(1, "Hello");
        map1.put(2, "There");
        final Map map2 = new HashMap();
        map2.put(2, "There");
        map2.put(3, "is");
        map2.put(4, "a");
        map2.put(5, "bird");
    
        // Add everything in map1 not in map2 to map2
        map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
    }
    

提交回复
热议问题