Summing a stream of integers into a long variable in Java

sank :

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?

Oleksandr Pyrohov :

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

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=442404&siteId=1