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();
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();
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