Sunday, January 23, 2022

Mutable multisets

The implementation of mutable multisets in Clojure deosn't contradict the currently existing multiset implementations in the Java platform, in particular the one provided by apache commons, because Java collections tend to be mutable. So in general we have different JVM datatypes for mutable and immutable collections. To use the mutable one just call up the apache commons collection library and import the multiset data type.
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 mlutisets in Clojure

No comments:

Post a Comment