1. Why can the reduce method from a Stream<Integer> can auto-unbox to a double, when it's returning an Integer ?
double sum = ls.stream().reduce(0, (a, b) -> a + b);
Hi Paul, I made the following trial, but still don't understand why the compiler gives me an error since the variables sum3 and sum4 outside the lambda expression are not even initialized
I tried to just declare the variable to go one step further and try to understand why the compiler consider the variable sum outside(initialized one single time/only declared) as non-effectively final
Q4_Streams.java:18: error: variable sum3 might not have been initialized
double sum3;ls.stream().peek(x->{sum3=sum3+x;}).forEach(y->{});
^
Q4_Streams.java:19: error: variable sum3 might not have been initialized
System.out.println(sum3);
^
Q4_Streams.java:20: error: variable sum4 might not have been initialized
double sum4;ls.stream().forEach(a->{sum4=sum4+a;});
^
Q4_Streams.java:21: error: variable sum4 might not have been initialized
System.out.println(sum4);
^
Q4_Streams.java:18: error: local variables referenced from a lambda expression must be final or effectively final
double sum3;ls.stream().peek(x->{sum3=sum3+x;}).forEach(y->{});
^
Q4_Streams.java:20: error: local variables referenced from a lambda expression must be final or effectively final
double sum4;ls.stream().forEach(a->{sum4=sum4+a;});
/code]
1. Well, local variables have to be initialized explicitly. In your code, sum3 isn't initialized. What value do you think the JVM will use while computing the expression sum3=sum3+x; for the first time? This is standard OCAJP stuff
2. If you want to use a local variable within a lambda expression, it also has be effectively final. Which means, you can't modify its value. What do you think sum3=sum3+x; is doing?
If you like our products and services, please help us by posting your review here.
Okay, many thanks. I thought that effectively-final was referring to variables that didn't change its value outside the lambda expression. I understand it now, you can't reassign the value at all