I was playing with Java's Optional and thought that it works like an if else block. But in the following code even if the name
variable is not null
the content of the orElse
block get's executed. Any explanation?
import java.util.Optional;
class Scratch {
public static void main(String[] args) {
String name = "some text";
System.out.println(
Optional.ofNullable(name)
.map(n -> mapped())
.orElse(getOrElse()));
}
static String mapped(){
System.out.println("mapped -- block executed");
return "mapped";
}
static String getOrElse(){
System.out.println("orElse -- block executed");
return "orElse";
}
}
Output:
mapped -- block executed
orElse -- block executed
mapped