Adam Lee Adam Lee - 1 year ago 180
Java Question

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download