import java.util.ArrayList;
import java.util.Arrays;
import org.apache.commons.collections4.multiset.HashMultiSet;
In order to create a multiset, it is good to first have a java.util.Collection created first. So to create one I simply using I simply use the asList method of the java.util.Arrays class.
// create a mutable multiset
var ms = new HashMultiSet < Integer > (Arrays.asList(1,2,2,2,3));
// print its curent contents
System.out.println(ms);
// add elements to the multiset to change it
ms.add(4);
ms.add(5);
// now the multiset is actually different
System.out.println(ms);
// remove the elements we added to change it back
ms.remove(4);
ms.remove(5);
// the multiset is back to its original state
System.out.println(ms);
There are slight differences in the API from the more familiar multiset implementation, like we use uniqueSet for what is commonly called the support in multiset theory and we use getCount to get the multiplicity of them element. But aside from a few terminology differences the apache commons provides everything you need to deal with multisets. It also provides a ton of other nice things like the best math library programmed in Java.
See also:
Immutable multisets in Clojure
No comments:
Post a Comment