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?
Use mapToLong(Integer::longValue)
instead of mapToInt(...)
:
long sum = numbers.stream().mapToLong(Integer::longValue).sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With