Here's what I've got so far:
Optional<Foo> firstChoice = firstChoice(); Optional<Foo> secondChoice = secondChoice(); return Optional.ofNullable(firstChoice.orElse(secondChoice.orElse(null)));
This strikes me as both hideous and wasteful. If firstChoice is present I am needlessly computing secondChoice.
There's also a more efficient version:
Optional<Foo> firstChoice = firstChoice(); if(firstChoice.isPresent()) { return firstChoice; } else { return secondChoice(); }
Here I can't chain some mapping function to the end without either duplicating the mapper or declaring another local variable. All of this makes the code more complicated than the actual problem being solved.
I'd much rather be writing this:
return firstChoice().alternatively(secondChoice());
However Optional::alternatively obviously doesn't exist. Now what?
So, to overcome this, Java 8 has introduced a new class Optional in java. util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run.
Optional is generally used as a return type for methods that might not always have a result to return. For example, a method that looks up a user by ID might not find a match, in which case it would return an empty Optional. Optional can help to reduce the number of null pointer exceptions in your code.
Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.
Try this:
firstChoice().map(Optional::of) .orElseGet(this::secondChoice);
The map method gives you an Optional<Optional<Foo>>
. Then, the orElseGet
method flattens this back to an Optional<Foo>
. The secondChoice
method will only be evaluated if firstChoice()
returns the empty optional.
Maybe something like this:
Optional<String> finalChoice = Optional.ofNullable(firstChoice() .orElseGet(() -> secondChoice() .orElseGet(() -> null)));
From: Chaining Optionals in Java 8
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