简体   繁体   中英

Sum of each values of Guava Multimap

I created a Guava Multimap ListMultimap<String,String> sampleMultimap = ArrayListMultimap.create(); And added some values which I take from a text file. Now as an output I have

{Football=[10], Basketball=[1210, 1210, 1210, 120], Tennis=[1, 10, 100, 1000]}

I would like to sum each of the sports and find the highest sum. So expected result is

Basketball: 3750

Somehow I am stuck because I cant get the each one with samleMultimap.get(x) because key values are unknown and comes form text file. Is there any way to get the expected result?

In the end you want Map<String, Integer> where values are sums of original multimap. You can use couple views:

  • Multimap#asMap() to have Map<K, Collection<V>> view of your multimap,
  • Maps#transformValues(Map, Function) - to create a view of a map where each value is transformed by a function .

     Map<String, Integer> map = Maps.transformValues(multimap.asMap(), ints -> ints.stream().mapToInt(Integer::intValue).sum());

Note that if you want to perform many operations on resulted map , read caveat in documentation and for example do ImmutableMap.copyOf(map) :

The function is applied lazily, invoked when needed. This is necessary for the returned map to be a view, but it means that the function will be applied many times for bulk operations like Map.containsValue(java.lang.Object) and Map.toString() . For this to perform well, function should be fast. To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

With a ListMultimap you can call asMap() to get a view as a java.util.Map , then do normal map things.

If you change sampleMultimap to be an ArrayListMultimap instead of ListMultimap , then you can call keySet() directly (skip the asMap() call) and iterate over the resulting keys.

Here's an example showing how you could get each key from a ListMultimap (even if the underlying implementation is an instance of ArrayListMultimap ), then get each associated value:

ListMultimap<String,String> sampleMultimap = ArrayListMultimap.create();
Map<String,String> mapView = sampleMultimap.asMap();
for (String key : mapView.keySet()) {
    String value = mapView.get(key);
    // do something with value
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM