Combine two Maps into a MultiMap

我只是一个虾纸丫 提交于 2019-12-06 18:38:15

问题


What is the best way to combine two Maps into a single Guava MultiMap in Java?

For example:

  • Map1 contains (1, a) and (2, b)
  • Map2 contains (2, c) and (3, d)

Then the resulting combined multimap would contain

  • (1, {a}), (2, {b, c}), and (3, {d})

This is my current solution:

Multimap<T, K> combineMaps(Map<T, K> map1, Map<T, K> map2) {
    Multimap<T, K> multimap = new MultiMap();
    for (final Map.Entry<T, K> entry : map1.entrySet()) {
        multimap.put(entry.getKey(), entry.getValue());
    }
    for (final Map.Entry<T, K> entry : map2.entrySet()) {
        multimap.put(entry.getKey(), entry.getValue());
    }
    return multimap;
}

回答1:


...What sort of multimaps are these? Are they from Guava, or some other library?

In Guava, you could do

multimap.putAll(Multimaps.forMap(map1));
multimap.putAll(Multimaps.forMap(map2));



回答2:


Your solution looks fine. You could initialize like this:

Multimap<T, K> multimap = new MultiMap(map1);

and then only iterate through the second map, however the complexity/speed is the same.



来源:https://stackoverflow.com/questions/9324154/combine-two-maps-into-a-multimap

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