将两个地图合并成一个MultiMap [英] Combine two Maps into a MultiMap

查看:125
本文介绍了将两个地图合并成一个MultiMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用Java将两个Map组合成一个Guava MultiMap的最佳方法是什么?

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

例如:

  • Map1包含(1,a)和(2,b)
  • Map2包含(2,c)和(3,d)

然后生成的组合多图将包含

Then the resulting combined multimap would contain

  • (1,{a}),(2,{b,c})和(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;
}

推荐答案

...这些是哪种多图?他们来自番石榴或其他图书馆吗?

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

在番石榴里,你可以做

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

这篇关于将两个地图合并成一个MultiMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆