Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LongStream to sum int array elements

Because many integers can overflow when summed, I needed a long stream to do the job but it wont accept int array. How can I convert each element at the time of streaming instead of using a long array?

// arr is an int[]
LongStream s = Arrays.stream( arr); // error
result = s.reduce(0, Long::sum); 

Edit: it appears that integer stream is turned into a long one using its method as in Tagir Valeev's answer.

LongStream asLongStream();

like image 345
huseyin tugrul buyukisik Avatar asked Sep 26 '15 12:09

huseyin tugrul buyukisik


1 Answers

Use IntStream.asLongStream() method:

LongStream s = Arrays.stream(arr).asLongStream();

By the way s.reduce(0, Long::sum) is the longer alternative for simple sum() method (which internally does the same):

long result = Arrays.stream(arr).asLongStream().sum();
like image 82
Tagir Valeev Avatar answered Oct 10 '22 14:10

Tagir Valeev