2014-02-18 71 views
3

我必須將Guava Multiset<String>轉換爲Map<String, Integer>(Key,Count)。將Multiset轉換爲地圖

我找不到任何實用功能。有沒有什麼比我的代碼短呢?

private static Map<String, Integer> multisetToMap(final Multiset<String> multiset) { 
    Map<String, Integer> result = new HashMap<>(); 
    for(String element: multiset.elementSet()) { 
     result.put(element, multiset.count(element)); 
    } 
    return ImmutableMap.copyOf(result); 
} 
+0

在http://codereview.stackexchange.com/上發佈這可能會更好。一種觀察是使用'ImmutableMap.Builder'而不是填充'HashMap'然後複製它。 –

+0

@PaulBellora'''Collections.unmodifiableMap()'''也是一個選項。 –

回答

1

事實上,有這個沒有隱藏番石榴功能,和你做基本上是正確的事情。

我沒有發現一個功能請求(開放或以其他方式)做這件事。但是如果我們實施this feature request你可能有另一種選擇。

2

如果您可以使用Eclipse Collections(以前稱爲GS Collections)包(相當於Multiset),則可以使用方法toMapOfItemToCount()

HashBag<Integer> bag = HashBag.newBagWith(1, 2, 2, 3, 3, 3); 
Map<Integer,Integer> map = bag.toMapOfItemToCount(); 
Assert.assertEquals(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), map); 

UnifiedMap是HashMap的替代替代品。

注:我是Eclipse集合的提交者。