Java Optional
last modified July 8, 2023
In this article we talk Optional type in Java.
Optional is a container object which may or may not contain a value.
We can check if a value is present with isPresent
and then retrive
it with get
. If the container does not contain a value it is then
called empty.
The goal of the Optional
type is to avoid null references and all
the problems that are caused by them.
The Optional
was inspired by similar types found in Haskell and
Scala. Other languages, such as C# or Groovy, use null-safe operators
.?
for the same purpose.
Optional<String> empty = Optional.empty();
We create an empty Optional
with Optional.empty
.
It is used insted of null references.
Optional<String> word = Optional.of("falcon");
Optional.of
is used when we are certain that the parameter will not
be null.
Optional<String> word = Optional.ofNullable(value);
Optional.ofNullable
is used when we don't know if there will be
null.
Java Optional simple example
In the following example, we have a simple example with Optional
type.
package com.zetcode; import java.util.Arrays; import java.util.Optional; public class OptionalEx { public static void main(String[] args) { var words = Arrays.asList("rock", null, "mountain", null, "falcon", "sky"); for (int i = 0; i < 5; i++) { Optional<String> word = Optional.ofNullable(words.get(i)); word.ifPresent(System.out::println); } } }
We have a list of words; the list also contains null values. We go through the list and print the elements.
Optional<String> word = Optional.ofNullable(words.get(i));
We know that we can get a null value from the list; therefore, we wrap the
element into Optional
with Optional.ofNullable
.
word.ifPresent(System.out::println);
We check if there is some value in the Optional
with
ifPresent
. If case there is one, we print it.
In the following example, we have three methods that return an
Optional
type.
package com.zetcode; import java.util.Optional; public class Optionals { public static void main(String[] args) { if (getNullMessage().isPresent()) { System.out.println(getNullMessage().get()); } else { System.out.println("n/a"); } if (getEmptyMessage().isPresent()) { System.out.println(getEmptyMessage().get()); } else { System.out.println("n/a"); } if (getCustomMessage().isPresent()) { System.out.println(getCustomMessage().get()); } else { System.out.println("n/a"); } } private static Optional<String> getNullMessage() { return Optional.ofNullable(null); } private static Optional<String> getEmptyMessage() { return Optional.empty(); } private static Optional<String> getCustomMessage() { return Optional.of("Hello there!"); } }
The three methods return a null message, an empty message and a real message.
if (getNullMessage().isPresent()) { System.out.println(getNullMessage().get()); } else { System.out.println("n/a"); }
First, we check if the value returned by the method contains a value with
isPresent
. If true, we get the value with get
.
Otherwise we print "n/a" message.
Java Optional ifEmpty
The ifEmpty
returns true, if the value is not present.
package com.zetcode; import java.util.Arrays; import java.util.Optional; public class OptionalIfEmpty { public static void main(String[] args) { var words = Arrays.asList("rock", null, "mountain", null, "falcon", "sky"); for (int i = 0; i < 5; i++) { Optional<String> word = Optional.ofNullable(words.get(i)); if (word.isEmpty()) { System.out.println("n/a"); } word.ifPresent(System.out::println); } } }
In the example, we print all valid values with ifPresent
. All empty
values are recognized via isEmpty
.
Java Optional orElse
The orElse
method allows us to quickly return a value if it is not
present.
package com.zetcode; import java.util.Optional; public class OptionalOrElse { public static void main(String[] args) { System.out.println(getNullMessage().orElse("n/a")); System.out.println(getEmptyMessage().orElse("n/a")); System.out.println(getCustomMessage().orElse("n/a")); } private static Optional<String> getNullMessage() { return Optional.ofNullable(null); } private static Optional<String> getEmptyMessage() { return Optional.empty(); } private static Optional<String> getCustomMessage() { return Optional.of("Hello there!"); } }
We managed to shorten the example a bit with orElse
method.
In this article we covered the Optional
type in Java.
Java Optional flatMap
The flatMap
method applies the provided mapping function to a
value if it is present. It returns that result or otherwise an empty
Optional
. If the result is already an Optional
,
flatMap
does not wrap it within an additional
Optional
.
package com.zetcode; import java.util.Arrays; import java.util.Optional; import java.util.function.Function; public class OptionalFlatMap { public static void main(String[] args) { Function<String, Optional<String>> upperCase = s -> Optional.of(s.toUpperCase()); var words = Arrays.asList("rock", null, "mountain", null, "falcon", "sky"); for (int i = 0; i < 5; i++) { Optional<String> word = Optional.ofNullable(words.get(i)); var res = word.flatMap(upperCase); res.ifPresent(System.out::println); } } }
In the example, we apply the upperCase
function on the list of
words.
Author
List all Java tutorials.