Search code examples
javaguavamultimap

Finding the sum of each ListMultiMap Key


I cannot find a simple way to find the sum of all keys within a ListMultiMap in Java.

I have a ListMultiMap: ListMultimap<String, Long> foodCals = ArrayListMultimap.create();

That contains different keys with multiple values within them:

["19/03/2020": 77, 88, 88], ["18/03/2020": 22, 33, 21], ["17/03/2020": 77, 33, 88]

How do you find the total of each Key? And get an output like: 1-253 , 2-76, 3-198.

Something like this:

int p = 0;
for(String s : foodCals.keySet()){
    System.out.Println(p + foodCals.sumOfKey(p)) //Print the index number + the sumOfKey (sumOfKey doesn't exist).
    p++;
}


Solution

  • There's no built-in function to do so, but treating the multimap as a Map (with asMap()) will give you a collection of the values per day. From there, you just need to sum them, e.g., by streaming them and converting them to primitives:

    int p = 0;
    for (Collection<Long> vals : foodCals.asMap().values()) {
        System.out.println(p + " - " + vals.stream().mapToLong(Long::longValue).sum());
        p++;
    }
    

    EDIT:

    For older Java versions (before 8), the same logic should apply, although the syntax is a bit clunkier, and you'll have to sum the values yourself:

    int p = 0;
    for (Collection<Long> vals : foodCals.asMap().values()) {
        long sum = 0L;
        for (Long val : vals) {
            sum += val;
        }
        System.out.println(p + " - " + sum);
        p++;
    }