问题
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