A Multiset is a collection that is similar to Set, but it may have duplicate elements. The duplicate elements are supported by maintaining a count of the total number of times an element appears in the collection. This post will cover Multiset interface provided by the Guava library in Java.

Since JDK doesn’t provide any implementation of the Multiset, programmers often switch to HashMap to store element-count pairs in Java. We have already seen how to implement Multiset class in Java using a List interface. Several third-party libraries also offer the Multiset implementation, such as Guava and Apache Commons Collections. This post will discuss common utility methods provided by Guava’s Multiset interface:

1. Using add() and contains() methods

We know that if two equal elements are added to java.util.Set, the second element will be discarded. The Guava Multiset, on the other hand, can store the duplicates. Any subsequent calls to the add() method for the same value will not be discarded. The following example demonstrates the usage of the add(), addAll(), contains(), and containsAll() methods provided by Guava’s Multiset interface.

Download Code

 
The above code creates a Multiset instance using the HashMultiset implementation of Multiset, which is backed by a HashMap. There are several other implementations provided by Guava, such as TreeMultiset, LinkedHashMultiset, ConcurrentHashMultiset, ImmutableMultiset, or ImmutableSortedMultiset.

2. Removing values from the Multiset

The Guava Multiset provides the remove(Object) method that removes a single occurrence of the specified element from the multiset. It also has the removeAll(Object, int) method that removes a specified number of occurrences of the specified element from the multiset. The following example demonstrates the use of these methods:

Download Code

3. Iterating over the Multiset

Multiset provides two collection views: elementSet() and entrySet(). The elementSet() method returns the distinct elements in the Multiset. The entrySet() method returns the Multiset.Entry instances that has both distinct elements and their count. We can also use elementSet().size() to know the number of unique elements in the multiset. The following example demonstrates the usage of the elementSet() and entrySet() methods:

Download Code

4. Immutable Multiset in Guava

An Immutable Multiset is a type of Multiset that does not allow modifications to its elements. The Guava Multiset interface has two immutable implementations: ImmutableMultiset and ImmutableSortedMultiset, which can be used over the mutable implementations if needed. We can easily create an ImmutableMultiset using a builder. For example, we can use something like this:

Download Code

That’s all about Multiset Interface by Guava in Java.

 
Reference: Multiset (Guava: Google Core Libraries for Java 31.0-jre API)