Java-8 – three possible Java 8 optional values – how do you cleanly return any existing?
•
Java
See English answers > teaching options in Java 8 5
return optionalA.orElseIfPresent(optionalB).orElseIfPresent(optionalC);
If all three are empty, an optional empty().
The existing orelse and orelseget do not really complete the task - they must return an actual value, so the remaining backup cannot be the optics itself
In the worst case, I can have a long list of ifpresent () checks, but there seems to be a better way to implement it?
Solution
return Stream.of(optional1,optional2,optional3)
return Stream.of(optional1,optional2,optional3) .filter(Optional::isPresent) .map(Optional::get) .findFirst();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码