HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to sum a list of integers with java streams?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withhowjavasumintegersliststreams

Problem

I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized?

Map integers;
integers.values().stream().mapToInt(i -> i).sum();

Solution

I suggest 2 more options:

integers.values().stream().mapToInt(Integer::intValue).sum();
integers.values().stream().collect(Collectors.summingInt(Integer::intValue));


The second one uses Collectors.summingInt() collector, there is also a summingLong() collector which you would use with mapToLong.

And a third option: Java 8 introduces a very effective LongAdder accumulator designed to speed-up summarizing in parallel streams and multi-thread environments. Here, here's an example use:

LongAdder a = new LongAdder();
map.values().parallelStream().forEach(a::add);
sum = a.intValue();

Code Snippets

integers.values().stream().mapToInt(Integer::intValue).sum();
integers.values().stream().collect(Collectors.summingInt(Integer::intValue));
LongAdder a = new LongAdder();
map.values().parallelStream().forEach(a::add);
sum = a.intValue();

Context

Stack Overflow Q#30125296, score: 185

Revisions (0)

No revisions yet.