[英]Guava: How to create an explicit Ordering from a List and a single element?
[英]In Guava, how to create a Multiset with a single element and n occurrences
我想在Guava中創建一個(不可變的)Multiset,它具有一個具有出現的occurrences
入口element
,這兩個在編譯時都不知道。
我想出的是這樣的:
ImmutableMultiset.<X>builder().addCopies(element, occurrences).build()
我想我正在尋找這樣的方法:
public static ImmutableMultiset<X> ImmutableMultiset.nOccurrencesOf(
X element, int occurrences){}
要么:
public static ImmutableMultiset<X> Multisets.singletonMultiset(
X element, int occurrences){}
我有沒有忽略任何使上述代碼更短的方法?
這是不使用構建器的單行解決方案。
ImmutableMultiset<X> multiset =
ImmutableMultiset.copyOf(Collections.nCopies(occurrences, element));
但是,這有一個缺點:其運行時間隨出現次數而定。 為了獲得更好的性能,請使用其他方法之一。
這是另一個選項,但看起來不如您介紹的builder選項好:
Multiset<X> set = HashMultiset.create();
set.add(element, occurrences);
ImmutableMultiset<X> immutableSet = ImmutableMultiset.copyOf(set);
番石榴的貢獻者在這里。
堅持建設者。 它已經非常簡單,只需一行就解決了這個問題。 這可能不是一個足夠普遍的情況,需要使用自己的特殊方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.