Merge two Maps of Maps in Java

情到浓时终转凉″ 提交于 2019-12-12 05:48:22

问题


I have a HashMap which in turn has a HashMap within,

Map<Long, Map<String, Double>> map = new HashMap<>();

I will have multiple inner maps for the same Long value, how do I make sure that the value field isn't replaced and rather merged (appended)?

This question differs from How to putAll on Java hashMap contents of one to another, but not replace existing keys and values? as it is about a Map of Strings, I'm stuck with a map of maps

For instance

    Map<Long, Map<String, Double>> map = new HashMap<>();
    Map<String, Double> map1 = new HashMap<>();
    Map<String, Double> map2 = new HashMap<>();

    map1.put("1key1", 1.0);
    map1.put("1key2", 2.0);
    map1.put("1key3", 3.0);

    map2.put("2key1", 4.0);
    map2.put("2key2", 5.0);
    map2.put("2key3", 6.0);

    map.put(222l, map1);
    map.put(222l, map2);

should give me 6 innermap entries for key '222' and not 3.


回答1:


If you are using Java 8, instead of put you can call a merge method:

map.merge(222L, map2, (m1, m2) -> {m1.putAll(m2);return m1;});

If map already had a value corresponding to given key, the merge function passed as third argument will be called which just adds the content of the new map to the previously existing one. Here's complete code:

Map<Long, Map<String, Double>> map = new HashMap<>();
Map<String, Double> map1 = new HashMap<>();
Map<String, Double> map2 = new HashMap<>();

map1.put("1key1", 1.0);
map1.put("1key2", 2.0);
map1.put("1key3", 3.0);

map2.put("2key1", 4.0);
map2.put("2key2", 5.0);
map2.put("2key3", 6.0);

map.merge(222L, map1, (m1, m2) -> {m1.putAll(m2);return m1;});
map.merge(222L, map2, (m1, m2) -> {m1.putAll(m2);return m1;});
System.out.println(map);

Prints all six keys:

{222={1key2=2.0, 1key3=3.0, 2key3=6.0, 2key1=4.0, 1key1=1.0, 2key2=5.0}}


来源:https://stackoverflow.com/questions/42240350/merge-two-maps-of-maps-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!