I have noticed that if I use Optional the following way:
Object returnValue = Optional.ofNullable(nullableValue)
.map(nonNullValue -> firstMethod(arg1, nonNullValue))
.orElse(secondMethod)
It is executing both the first method and second method when the nullableValue is not null. Am I doing something wrong? I want it to execute only firstMethod when nullableValue is not null.
map and flatMap seems to have preCondition ( if(!isPresent()
). but, orElse doesn't. How can I write my code using java8 without using if not null condition?
Based on comments, sample code:
public static String firstMethod(String someString) {
System.out.println("In first method");
return someString;
}
public static String secondMethod() {
System.out.println("In second method");
return "secondMethod";
}
public static void main(String a[]) {
String nullableString = "nonNullString";
String result = Optional.ofNullable(nullableString)
.map(nonNullString -> firstMethod(nonNullString))
.orElse(secondMethod());
System.out.println("Result: "+result);
}
Output:
In first method
In second method
Result: nonNullString
You are calling the second method to pass as a parameter to the orElse()
call. The orElse()
is not the one calling secondMethod()
like what happens in the map
call. You are passing the returned value from secondMethod()
not the method itself.
What you want to do:
Optional.ofNullable(nullableValue).map(MyClass::firstMethod).orElseGet(MyClass::secondMethod);
What this does it is casts secondMethod into a supplier. That way it is only called when the optional is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With