davidrpugh davidrpugh - 5 months ago 29
Java Question

Add(remove) element(s) from an ImmutableSortedMultiset

I am struggling how to perform basic operations using a Guava ImmutableSortedMultiset...


  • How would one create a copy of an existing ImmutableSortedMultiset that is contains a new element?

  • How would one create a copy of an existing ImmutableSortedMultiset where one of the elements has been removed?



If possible, I would like to be able to perform these operations without sorting the existing collection each time a new element is added(removed).

Answer

I don't think you can do it without rebuilding a new ImmutableSortedMultiset. Assuming you have an original multiset, I would start by making a composite view using the methods in Multiset:

// View with one more element
Multiset<String> view = Multisets.union(original, ImmutableMultiset.of("a"));

or

// View with one less element
Multiset<String> view = Multisets.difference(original, ImmutableMultiset.of("a"));

followed by creation of the immutable sorted copy:

ImmutableSortedMultiset<String> copy = ImmutableSortedMultiset.copyOf(view);