Ath now
Ath now

Reputation: 37

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++;
}

Upvotes: 2

Views: 177

Answers (2)

Naman
Naman

Reputation: 31958

You might just be looking to sum the values per key while iterating over the keySet:

ListMultimap<String, Long> foodCals = ArrayListMultimap.create();
Map<String, Long> summingEntries = foodCals.keySet()
        .stream()
        .collect(Collectors.toMap(k -> k,
                k -> foodCals.get(k).stream()
                        .mapToLong(i -> i).sum()));

This would result in

{19/03/2020=253, 17/03/2020=198, 18/03/2020=76}

A similar logic without Streams and lambdas would be:

Map<String, Long> summingEntries = new HashMap<>();
for (String k : foodCals.keySet()) {
    long sum = 0L;
    for (Long i : foodCals.get(k)) {
        sum += i;
    }
    if (summingEntries.put(k, sum) != null) {
        throw new IllegalStateException("Duplicate key");
    }
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311778

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++;
}

Upvotes: 1

Related Questions