This post will discuss how to implement a Multiset in Java.

A Multiset is a collection similar to a set that doesn’t guarantee any particular ordering on its elements, but it can accommodate duplicate elements, unlike Set. It supports duplicates by maintaining a count of the total number of occurrences of each element in the collection. Counting the frequency of elements is a very common operation in Java. We can use MultiSet to efficiently find the most frequent letter in a file or sort a limited range array.

We know that Java doesn’t provide Multiset implementation, so programmers often switch to HashMap to store the total number of times each key occurs. Although both Google Guava library and Apache Commons Collections provide Multiset implementation, wouldn’t it be great to implement our own Multiset class in Java?

 
Well, writing a Multiset class is actually very simple in Java. Following is a simple implementation of the Multiset class in Java that uses two lists – one to store the distinct elements and another to store their counts. Since list is used, the time complexity for most operations is linear in terms of the total number of distinct elements. A hash table is recommended over a list for optimal constant-time operations.

Download  Run Code

Output:

[USA x 2, Japan x 3, India x 2, China x 2]
[USA x 2, Japan, India x 2, China]
[USA x 4, Japan x 5, India x 2, Mexico x 3]

That’s all about Multiset implementation in Java.

 
Also See:

Google Guava’s Multiset Interface in Java

Implement a Multimap in Java

 
References: Multiset (Guava: Google Core Libraries for Java 23.0 API)