Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a list of integers with java streams?

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<String, Integer> integers; integers.values().stream().mapToInt(i -> i).sum(); 
like image 368
membersound Avatar asked May 08 '15 13:05

membersound


People also ask

How do you find the sum of a stream of integers?

We can use mapToInt() to convert a stream integers into a IntStream . int sum = integers. stream(). mapToInt(Integer::intValue).

How do you sum a List of numbers in Java?

A simple solution to calculate the sum of all elements in a List is to convert it into IntStream and call sum() to get the sum of elements in the stream. There are several ways to get IntStream from Stream<Integer> using mapToInt() method.


2 Answers

This will work, but the i -> i is doing some automatic unboxing which is why it "feels" strange. mapToInt converts the stream to an IntStream "of primitive int-valued elements". Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:

integers.values().stream().mapToInt(i -> i.intValue()).sum(); integers.values().stream().mapToInt(Integer::intValue).sum(); 
like image 186
Necreaux Avatar answered Sep 25 '22 19:09

Necreaux


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(); 
like image 37
Alex Salauyou Avatar answered Sep 22 '22 19:09

Alex Salauyou