Java 9 Improved Optional Class
The Optional class was introduced in Java 8 and has been effective in handling null pointer exceptions. In Java 9, three methods have been added to enhance its functionality:
- stream()
- ifPresentOrElse()
- or()
stream() Method
Syntax
public Stream<T> stream()
The stream method converts an Optional into a Stream. If the Optional contains a value, it returns a Stream containing that value; otherwise, it returns an empty Stream (Stream.empty()).
Example
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Tester {
public static void main(String[] args) {
List<Optional<String>> list = Arrays.asList(
Optional.empty(),
Optional.of("A"),
Optional.empty(),
Optional.of("B"));
// Filter the list to print non-empty values
// If the optional is non-empty, get the value in the stream, otherwise return an empty stream
List<String> filteredList = list.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
// Optional::stream method will return a stream of either one or zero elements if data is present or not
List<String> filteredListJava9 = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(filteredList);
System.out.println(filteredListJava9);
}
}
Execution output:
[A, B]
[A, B]
ifPresentOrElse() Method
Syntax
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
The ifPresentOrElse method includes an "else" clause, accepting two parameters: a Consumer and a Runnable.
The purpose of the ifPresentOrElse method is to call the function action with the contained value if the Optional contains a value, i.e., action.accept(value), which is consistent with ifPresent. The difference from ifPresent is the second parameter, emptyAction — if the Optional does not contain a value, ifPresentOrElse will call emptyAction, i.e., emptyAction.run().
Example
import java.util.Optional;
public class Tester {
public static void main(String[] args) {
Optional<Integer> optional = Optional.of(1);
optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () ->
System.out.println("Not Present."));
}
}
System.out.println("Not Present.");
optional = Optional.empty();
optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () -> System.out.println("Not Present."));
}
}
Execution output:
Value: 1
Not Present.
or() Method
Syntax
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
Example
import java.util.Optional;
import java.util.function.Supplier;
public class Tester {
public static void main(String[] args) {
Optional<String> optional1 = Optional.of("Mahesh");
Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present");
optional1 = optional1.or(supplierString);
optional1.ifPresent(x -> System.out.println("Value: " + x));
optional1 = Optional.empty();
optional1 = optional1.or(supplierString);
optional1.ifPresent(x -> System.out.println("Value: " + x));
}
}
Execution output:
Value: Mahesh
Value: Not Present