Search code examples
javaarraylistguavamultimap

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?


Solution

  • 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.