Java 9 - Optional Additions
In Java 8, the
java.util.Optional class was introduced (JavaDoc) as a way to define method return types where there is a need to return no result, and where
null is not a good fit as it needs to be explicitly mentioned that an empty return value is indeed possible.
In this article we will have a look at the
Optional methods which were added with Java 9.
Hint: in case you wonder about the method references in this article, it is using the method reference syntax from Java 8. In the code examples, we use jshell, a new command-line tool being part of Java 9 JDK.
Optional::ifPresentOrElse is used on
Optional instances to execute a lambda being a
java.util.function.Consumer if the value exists, or a
Runnable - or so-called empty action - if the value does not exist.
In the code snippet from above, the first lamda defines the
Consumer implementation which prints out the given
String argument to stdout. The second lamda defines the
Runnable implementation without an argument.
The use-case for
Optional::or should be relatively self-explanatory. If called on an
Optional, it returns the optional itself if its value exists or the
Optional created by the given
java.util.function.Supplier function (JavaDoc).
The code snippet above in fact does not use the given
Supplier function which would return
As the return type of
or is an
Optional, it’s perfectly valid to chain multipe
stream method is the most useful addition (imho). If a value is present, it returns a
java.util.stream.Stream instance containing only the optional value.
Maybe its usefulness might not be visible at first sight, however, when dealing with
Stream-typed return values it indeed makes sense to return a
Stream either based on an
Optional or on any other
In this article we showed the latest additions to
java.util.Optional in JDK 9, the most useful addition being the new