Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 426
sank Avatar asked Apr 20 '18 19:04

sank


1 Answers

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

long sum = numbers.stream().mapToLong(Integer::longValue).sum();
like image 184
Oleksandr Pyrohov Avatar answered Nov 15 '22 19:11

Oleksandr Pyrohov