In Guava, how to create a Multiset with a single element and n occurrences

1.2k Views Asked by At

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?

3

There are 3 best solutions below

1
On BEST ANSWER

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.

1
On

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);
1
On

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.