Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299038

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

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?

Upvotes: 0

Views: 1285

Answers (3)

Jared Levy
Jared Levy

Reputation: 2026

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.

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198211

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.

Upvotes: 1

John B
John B

Reputation: 32969

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

Upvotes: 1

Related Questions