bisarch
bisarch

Reputation: 1398

Summing a stream of integers into a long variable in Java

I have a Java Set, which contains some Integer elements. I want to sum its elements using Java 8 streams.

Set<Integer> numbers = new HashSet<>();
// Some code that will populate numbers
int sum = numbers.stream().mapToInt(Integer::intValue).sum() //Can overflow!

I could use the above code to get the sum but contents of numbers are Integer elements well below Integer.MAX_VALUE and there are a large number of them such that their sum could overflow. How do I convert the stream of Integer elements a stream of Long elements and sum it safely?

Upvotes: 10

Views: 4881

Answers (2)

nitnamby
nitnamby

Reputation: 414

mapToLong method would be the right one to use. It should avoid the overflow problem since computation is done as long.

long sum=numbers.stream().mapToLong(Number::longValue).sum();

Upvotes: 1

Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16226

Use mapToLong(Integer::longValue) instead of mapToInt(...):

long sum = numbers.stream().mapToLong(Integer::longValue).sum();

Upvotes: 13

Related Questions