Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top