I have to ensure if two values are non null. When the first and second have non null values, pass first as argument to second. If one of them are null value, then return false. This can be done in the following piece of code:
String value1 = function_to_get_value1() if (value1 == null) return false; String value2 = function_to_get_value2(value1) if (value2 == null) return false; return true;
It can also be done in short form:
try { return function_to_get_value2(function_to_get_value1()) != null; } catch (NullPointerException e) { return false; }
I was wondering how to do this in fluent form with Optional.
Advertisement
Answer
You could try something like this:
return Optional.ofNullable(function_to_get_value1()) .map(v1 -> function_to_get_value2(v1)) .isPresent();
map()
applies the lambda if value is present and returns a new Optional.ofNullable()
or otherwise returns an empty Optional
. So in the end you have an empty Optional
if either value was null or a non-empty one.
If you have a look at the source code for those methods, it basically is equivalent to this:
//Optional.ofNullable(...) Optional<UiObject> v1Opt = value1 == null ? Optional.empty() : Optional.of(value1); //Optional.map(...) Optional<UiObject> v2Opt; if(v1Opt.isPresent()) { //this is the lambda UiObject value2 = function_to_get_value2(value1); //Optional.ofNullable(...) called in map(...) v2Opt = value2 == null ? Optional.empty() : Optional.of(value2); } else { v2Opt = Optional.empty(); } //Optional.isPresent() return v2Opt.value != null;