Doing these 2 equivalent printouts I’m getting different results:
String text = "hi";
String text2 = null;
System.out.println(Optional.ofNullable(text).map(String::length).orElseGet(text2::length));
System.out.println(Optional.ofNullable(text).map(String::length).orElseGet(() -> text2.length()));
In the first case I’m getting a nullpointerexception, but in the second case I’m just getting “2” by console.
I understood the orElseGet part was never going no be evaluated if the Optional.ofNullable() part is not null, but I’m surprised to find that it is depending on the format of the functional expression used.
Why is this happening? I’m using java 11.0.21.
Thanks.