user1955934
user1955934

Reputation: 3495

Map Stream Get Total of Product of Key and Value

Given a Map<Long, Integer>, using java 8 map stream, how do you calculate the total

sum of all Entries in a Long result variable?

For example:[{100:1}, {100,2}]

result = (100*1) + (100*2) = 300

This is how i do it using iteration:

Map<Long, Integer> map = //init map
Long sum = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
    sum+= (entry.getKey() * entry.getValue());
}

Im thinking of something along this:

map.entrySet().stream()
.forEach(entry -> entry.getKey() * entry.getValue())
.sum()

Upvotes: 4

Views: 1079

Answers (2)

Pratik Pawar
Pratik Pawar

Reputation: 91

You can use below code for the same, here I have used java 8 stream reduce method :

Long totalSum= map.entrySet().stream().map(e-> e.getKey() * e.getValue()).reduce(0L, (s, i)-> s+i); System.out.println("Total sum "+ totalSum);

Upvotes: 0

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

This should do the trick.

long sumOfProducts = map.entrySet().stream().mapToLong(e -> e.getKey() * e.getValue()).sum();

Upvotes: 4

Related Questions