使用重复键合并两个地图(Map <string,map <string,=“”object =“”>&gt;)

时间:2016-02-13 08:37:03

标签: java hashmap guava multimap

我有两个来自番石榴的ImmutableMaps,我试图将它们组合在一起,它们可以有重复的键;

Map<String, Map<String, Object>> map1 = new ImmutableMap.Builder<String, Map<String, Object>>()
        .put("config", ImmutableMap.of(
                "key1", "value1",
                "key2", "value2"))
        .put("categoryapproval", ImmutableMap.of("reason_code", "listing_quality"))
        .build();

Map<String, Map<String, Object>> map2 = new ImmutableMap.Builder<String, Map<String, Object>>()
        .put("config", ImmutableMap.of(
                "key1", "value3",
                "key4", "value4"))
        .build();

所以,我不能使用putAll()方法,因为它会抛出DuplicateKeyException,这是预期的。我想要获得的输出就像是;

"config" --> "key1": {value1, value3},
             "key2": {value2},
             "key4": {value4}

最后,我还尝试了MultiValueMap,但MultiValueMap将值保持为List,我需要迭代。在map1我可以通过value1得到map1.get("config").get("key1"),其中value1可以是任何类型的对象。我感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用Guava的Multimap和Java 8&#39; {<3}}:

Map<String, Multimap<String, Object>> merged = new HashMap<>();
BiFunction<Multimap<String, Object>, Multimap<String, Object>, Multimap<String, Object>> remappingFunction = (value1, value2) -> {
    Multimap<String, Object> multimap = HashMultimap.<String, Object>create();
    multimap.putAll(value1);
    multimap.putAll(value2);
    return multimap;
};
map1.forEach((key, value) -> merged.merge(key, Multimaps.forMap(value), remappingFunction));
map2.forEach((key, value) -> merged.merge(key, Multimaps.forMap(value), remappingFunction));
merged.get("config").get("key1");

如果您不使用Java 8,那么您需要以其他方式管理多图的合并,但这个想法是一样的。