Question

I'd like to create an (immutable) Multiset in Guava that has a single entry element with occurrences occurrences, both of which are not known at compile time.

What I've come up with is this:

ImmutableMultiset.<X>builder().addCopies(element, occurrences).build()

I guess I was looking for a method like this:

public static ImmutableMultiset<X> ImmutableMultiset.nOccurrencesOf(
X element, int occurrences){}

or:

public static ImmutableMultiset<X> Multisets.singletonMultiset(
X element, int occurrences){}

Is there any method I have overlooked that makes the above code shorter?

Was it helpful?

Solution

Guava contributor here.

Stick with the builder. It already addresses the problem quite simply, and in a single line; it's probably not a common enough case to require its own special method.

OTHER TIPS

Here's a one-line solution that doesn't use a builder.

ImmutableMultiset<X> multiset = 
  ImmutableMultiset.copyOf(Collections.nCopies(occurrences, element));

However, this has one drawback: its run time scales with the number of occurrences. For better performance, use one of the other methods.

Here is another option but it doesn't seem as good as the builder option you presented:

Multiset<X> set = HashMultiset.create();
set.add(element, occurrences);
ImmutableMultiset<X> immutableSet = ImmutableMultiset.copyOf(set);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top