Multiset Interface
Multiset interface extends ‘Set’ to have duplicate elements, and provides various utility methods to deal with the occurrences of such elements in a set.
package org.fool.guava.collections; import java.util.Set; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; public class MultisetTest { public static void main(String[] args) { HashMultiset<String> multiset = HashMultiset.create(); multiset.add("a"); multiset.add("b"); multiset.add("c"); multiset.add("d"); multiset.add("a"); multiset.add("b"); multiset.add("c"); multiset.add("b"); multiset.add("b"); multiset.add("b"); // print the occurrence of an element System.out.println("Occurrence of 'b' : " + multiset.count("b")); // print the total size of the multiset System.out.println("Total Size : " + multiset.size()); // get the distinct elements of the multiset as set System.out.println("Set ["); Set<String> set = multiset.elementSet(); set.forEach(s -> System.out.println(s)); System.out.println("]"); // display all the elements of the multiset System.out.println("MultiSet ["); multiset.forEach(ms -> System.out.println(ms)); System.out.println("]"); // display the distinct elements of the multiset with their occurrence // count System.out.println("MultiSet ["); for (Multiset.Entry<String> entry : multiset.entrySet()) { System.out.println("Element: " + entry.getElement() + ", Occurrence(s): " + entry.getCount()); } System.out.println("]"); // remove extra occurrences multiset.remove("b", 2); // print the occurrence of an element System.out.println("Occurence of 'b' : " + multiset.count("b")); } }
output
Occurrence of 'b' : 5 Total Size : 10 Set [ a b c d ] MultiSet [ a a b b b b b c c d ] MultiSet [ Element: a, Occurrence(s): 2 Element: b, Occurrence(s): 5 Element: c, Occurrence(s): 2 Element: d, Occurrence(s): 1 ] Occurence of 'b' : 3