I am a bit confused about the behavior of Java lambdas and methods. For example, we have this code:
import java.util.function.Consumer; public class Main { private static StringBuilder sBuilder = new StringBuilder("1"); public static void main(String[] args) { Consumer<String> consumer = s -> sBuilder.append(s); sBuilder = new StringBuilder("2"); consumer.accept("3"); System.out.println(sBuilder); } }
Output:
23
This works as expected, but if we replace
s β sBuilder.append (s)
from
sBuilder :: Append
the output will be:
2
Do you have any idea how to explain this? Is this not the same thing? Thanks.
java lambda java-8 method-reference
j2esu
source share