Java SE 8 IntStream.reduce(..) (etc) seems to be operating inconsistently

Monday, May 12, 2014

I'm looking at various aspects of Java SE 8. I've encountered a number of situations where compilable code leads to runtime exceptions or apparent inconsistencies. Here is one, where a construct operates as expected in one context, but appears to fail in another. Is it a bug or am I missing something?



import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.DoubleStream;
import static java.lang.System.*;

public class Stream06 {
public static void main(String[] args) {
out.println(IntStream.rangeClosed(2,5)
.reduce((i,j)->i+j).getAsInt()); // OK
out.println(IntStream.rangeClosed(2,5)
.reduce(0,(i,j)->i+j)); // OK
out.println(IntStream.rangeClosed(2,5)
.reduce((i,j)->i*j).getAsInt()); // OK!
out.println(IntStream.rangeClosed(2,5)
.reduce(0,(i,j)->i*j)); // zero!!!

out.println();
out.println(LongStream.rangeClosed(2,5)
.reduce((l,m)->l+m).getAsLong()); // OK
out.println(LongStream.rangeClosed(2,5)
.reduce(0,(l,m)->l+m)); // OK
out.println(LongStream.rangeClosed(2,5)
.reduce((l,m)->l*m).getAsLong()); // OK!
out.println(LongStream.rangeClosed(2,5)
.reduce(0,(l,m)->l*m)); // zero!!!

out.println();
out.println(DoubleStream.of(2.5, 1.3, 6.8)
.reduce((d,e)->d+e).getAsDouble()); // OK
out.println(DoubleStream.of(2.5, 1.3, 6.8)
.reduce(0,(d,e)->d+e)); // OK
out.println(DoubleStream.of(2.5, 1.3, 6.8)
.reduce((d,e)->d*e).getAsDouble()); // OK (usual rounding issue)
out.println(DoubleStream.of(2.5, 1.3, 6.8)
.reduce(0,(d,e)->d*e)); // zero!!!
}
}






http://ift.tt/1gu7qS4