23

I see many examples about multimap but did not understand why Google Gauva is different?

Multimap<Integer, Set<String>> option4 = HashMultimap.create(); // Gauva

Map<Integer, Set<String>> opt = new HashMap<Integer, Set<String>>(); //Core Java

Is both above are behave same for holding data or different?

2
  • Read this Guava Wiki page. Commented Oct 7, 2013 at 10:56
  • 4
    Your first definition is not equivalent to the second one. Either the second one should be Map<Integer, Set<Set<String>>> (I doubt that this is what you needed), or the first one should be Multimap<Integer, String>. Commented Oct 7, 2013 at 13:34

5 Answers 5

34

A MultiMap<A, B> associates a key of type A with a value of type Collection<B> (hence the name MultiMap)

A Map<A, B> associates a key of type A with a value of type B.

So, a MultiMap<Integer, Set<String>> can be viewed as a Map<Integer, Collection<Set<String>>. This should be obvious by reading the api documentation.

1
  • 2
    that was pretty straightforward & hence helpful :) Commented Jul 26, 2016 at 13:55
20

The difference is that with the second, Core Java implementation, you need to check whether the Set is there before you insert. Guava's Multimap takes care of that for you.

With Core Java:

Set<String> innerSet = opt.get(key);
if (innerSet == null) {
    innerSet = new HashSet<String>();
    opt.put(key, innerSet);
}
innerSet.add(value);

With Guava:

opt.put(key, value);

Guava takes care of initialising an otherwise absent Set to store the values, takes care of any threading issues (eg stops two threads from creating a new Set for the same key in parallel) and also provides a few useful methods that you'd otherwise need to implement by hand, such as getting all the values across all the Sets.

0
7

You misunderstood something. These are not even roughly equivalent:

Multimap<Integer, Set<String>> option4 = HashMultimap.create(); // Guava
Map<Integer, Set<String>> opt = new HashMap<Integer, Set<String>>(); //Core Java

In your example, opt4 would map a single Integer to a Collection of Sets of Strings. That's exactly the point of using a Multimap, you don't have to explicitly deal with the second dimension. So in fact, the correct (equivalent) declaration would be:

SetMultimap<Integer, String> multimap = HashMultimap.create(); // Guava

and you can get a map view like this:

Map<Integer, Set<String>> mapView = multimap.asMap();
3

Nope, MultiMap means that there would be a collection of objects attached to each key. Documentation: Multimap_Is_Not_A_Map

0

First of all com.google.common.collect.Multimap is not java.util.Map, it is in a separate hierarchy.

Secondly, you can all the operations with Map<Integer, Set<String>> that Multimap interface requires but you will have to implement them yourself while HashMultimap offers ready implementation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.