Adam Lee
Adam Lee

Reputation: 25768

Guava MultiSet vs Map?

My understanding of Multiset is a set with frequency, but I can always use Map to represent the frequency, is there other reason to use Multiset?

Upvotes: 17

Views: 6142

Answers (2)

Arend von Reinersdorff
Arend von Reinersdorff

Reputation: 4233

Advantages of a Multiset<E> over a Map<E, Integer>:

  • No special code required when adding an element that is not already in the collection.
  • Methods for handling the count of elements directly: count(E), add(E, int), etc.
  • The intention of the code is clearer. A Multiset<E> obviously maps the elements to their counts. A Map<E, Integer> could map the elements to arbitrary integers.

See also:

Multiset Javadoc

Multiset explained in the Guava Wiki

Upvotes: 31

ColinD
ColinD

Reputation: 110054

To me, the most important point that sets Multiset apart from a Map is that it's a Collection: you just put stuff into it and you can get counts later. It conceptually fits the use cases for which it's designed where a Map does not. For those use cases, a Map is just a hack that kinda-sorta works OK since Java didn't provide anything more appropriate.

Upvotes: 9

Related Questions