In the previous post, we have seen how to implement Multiset class in Java, which allowed duplicate elements, unlike java.util.Set. This post will discuss about common utility methods provided by Multiset Interface of Apache Commons Collections.

The MultiSet is an interface provided by Apache Commons Collections library. It is similar to a set, but it allows duplicate elements. It supports duplicates by maintaining a count of the total number of occurrences of each element in the collection. Some of the methods provided by the Multiset Interface are:

  • add(E object): Add one copy of the specified object to the Multiset.
  • add(E object, int occurrences): Adds a number of occurrences of the specified object to the Multiset.
  • remove(Object object): Remove one occurrences of the specified object from the Multiset.
  • remove(Object object, int occurrences): Removes a number of occurrences of the specified object from the Multiset.
  • setCount(E object, int count): Sets the number of occurrences of the specified object in the Multiset to the given count.
  • getCount(Object object): Returns the number of occurrences of the given object currently in the Multiset.
  • entrySet(): Returns a Set of all entries contained in the Multiset.
  • uniqueSet(): Returns a Set of unique elements in the Multiset.
  • iterator(): Returns an iterator over the entire set of elements in the Multiset.

 
The standard implementation of the Multiset Interface is the HashMultiSet class, which uses a HashMap. Following is a simple Java program to demonstrate various utility methods provided by Apache Commons’s MultiSet interface:

Download Code

That’s all about Multiset Interface by Apache Commons Collections in Java.

 
Also See:

Google Guava’s Multiset Interface in Java

 
Reference: MultiSet (Apache Commons Collections 4.1 API)