I have to choose between two String variables - the first that has non null
value.
If they are both null
- then I want to exit the method.
This can be done in the following piece of code:
String value1 = <get from somewhere>
String value2 = <get from somewhere else>
String target = null;
if (value1 != null) target = value1;
else if (value2 != null) target = value2;
if (target == null) return null;
It can also be done in short form:
String target = value1 != null ? value1 : value2 != null ? value2 : null;
if (target == null) return null;
I am struggling with how to do this in fluent form with Optional
Note: I can only use Java 8 syntax (so no Optional.or()
)
Let's learn how to use Java 8's Optionals to make your null checks simple and less error-prone! Join the DZone community and get the full member experience. The method orElse() is invoked with the condition "If X is null, populate X. Return X.", so that the default value can be set if the optional value is not present.
Optional is a new type introduced in Java 8. It is used to represent a value that may or may not be present. In other words, an Optional object can either contain a non-null value (in which case it is considered present) or it can contain no value at all (in which case it is considered empty).
Creating Optional objects Also, by using ofNullable , you can create an Optional object that may hold a null value: Optional<Soundcard> sc = Optional. ofNullable(soundcard); If soundcard were null, the resulting Optional object would be empty.
We can get rid of all those null checks by utilizing the Java 8 Optional type. The method map accepts a lambda expression of type Function and automatically wraps each function result into an Optional . That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the hood.
String target = Optional.ofNullable(value1).orElse(value2)
If value1 == null
, then return value2
- which either has a value or is null. There is no need to explicitly handle the case of value2 == null
by mapping it to null.
If you have just two options, you could do it with:
target = Optional.ofNullable(value1)
.orElseGet(() -> Optional.ofNullable(value2).orElse(null));
Even if this can be made to work for more that two variables.
With java-9, this could be made a bit more readable:
target = Optional.ofNullable(value1)
.or(() -> Optional.ofNullable(value2))
.orElse(null);
The other answer has a very good point, indeed; thus this can be further simplified to not use Optional
s, at all, still a single line:
target = value1 != null ? value1 : value2;
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