In Optional while optional.orElse method is call, irrespective of the element is present or not the orElse part is executed it does not behave as the if else condition.
In the below code if you see in Case 1 both getNullPoJo and getDefaultPoJo is executed since getNullPoJo will return empty Optional
In Case 2 where you will get a Optional with loaded value (from getLoadedPoJo) also you getDefaultPoJo is executed
I am just trying to understand the working of optional.orElse.
public static void main (String [] a) {
PoJo poJo1=getNullPoJo().orElse(getDefaultPoJo());//Case 1
System.out.println("pojo1 Got "+poJo1.getVariable());
PoJo poJo2=getLoadedPoJo().orElse(getDefaultPoJo());//Case 2
System.out.println("pojo2 Got "+poJo2.getVariable());
}
private static Optional<PoJo> getNullPoJo() {
System.out.println("Executing getNullPoJo");
Optional<PoJo> optional=Optional.empty();
return optional;
}
private static Optional<PoJo> getLoadedPoJo() {
System.out.println("Executing getLoadedPoJo");
PoJo poJo =new PoJo();
poJo.setVariable("Loaded");
Optional<PoJo> optional=Optional.of(poJo);
return optional;
}
private static PoJo getDefaultPoJo() {
System.out.println("Executing getDefaultPoJo");
PoJo poJo =new PoJo();
poJo.setVariable("Default");
return poJo;
}
The current Output is:
Executing getNullPoJo
Executing getDefaultPoJo
pojo1 Got Default
Executing getLoadedPoJo
Executing getDefaultPoJo
pojo2 Got Loaded
My Expected Output is:
Executing getNullPoJo
Executing getDefaultPoJo
pojo1 Got Default
Executing getLoadedPoJo
pojo2 Got Loaded
I do not want the call to getDefaultPoJo in Case 2