An Optional class provides a container that may or may not contain a non-null value. This Optional class introduced in Java 8 to reduce the number of places in the code where a NullPointerException can be generated. Java 9 added three new methods to Optional class: or(), ifPresentOrElse() and stream() that help us to deal with default values.
Optional.or()
The or() method introduced in Java 9 and the parameter of this method is a functional interface Supplier. This method always gives us an Optional object that is not empty. If the Optional object is not empty, it returns the Optional object itself. Otherwise, it returns an Optional object that the Supplier creates.
Example
import java.io.IOException; import java.util.Optional; public class OptionalOrMethodTest { public static void main(String[] args) throws IOException { String str = null; Optional<String> opt = Optional.ofNullable(str); Optional<String> result = opt.or(() -> Optional.of("Adithya")); System.out.println(result); } }
Output
Optional[Adithya]
Optional.ifPresentOrElse()
The ifPresentOrElse() method introduced in Java 9. It is similar to the ifPresent() method with one difference is that we have added one more Runnable parameter. In case, if an Optional object is empty, the object of the Runnable interface can be executed.
Example
import java.util.Optional; public class OptionalIfPresentOrElseTest { public static void main(String[] args) { String str = null; Optional<String> opt = Optional.ofNullable(str); opt.ifPresentOrElse( x -> System.out.println(x), () -> System.out.println("No value")); } }
Output
No value
Optional.stream()
The Optional.stream() method is supported since Java 9. This method can be used to create a new stream object from an Optional object. If an Optional object contains a value, it returns the stream object containing that value.
Example
import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.stream.Stream; public class OptionalStreamMethodTest { public static void main(String[] args) throws IOException { List<Optional<String>> list = List.of( Optional.of("Jai"), Optional.empty(), Optional.of("Adithya")); Stream<String> stream = list.stream().flatMap(Optional::stream); stream.forEach(System.out::println); } }
Output
Jai Adithya