Skip to main content
Java 9 · Topic 5 of 6

Optional additions

Definition​

Java 9 added ifPresentOrElse (do one thing if there is a value, another if not), or (try another Optional) and stream (turn an Optional into a stream of zero or one items).

Example code​

Handling both cases without an if statement

import java.util.List;
import java.util.Optional;

class Demo {
public static void main(String[] args) {
Optional<String> found = Optional.of("Asha");
Optional<String> missing = Optional.empty();

found.ifPresentOrElse(n -> System.out.println("Hello " + n), () -> System.out.println("nobody"));
missing.ifPresentOrElse(n -> System.out.println("Hello " + n), () -> System.out.println("nobody"));

System.out.println(missing.or(() -> Optional.of("backup")).get()); // try another source

List<String> names = List.of("Asha", "Ravi").stream()
.map(n -> n.equals("Ravi") ? Optional.<String>empty() : Optional.of(n))
.flatMap(Optional::stream) // drops the empty ones
.toList();
System.out.println(names);
}
}

// Output:
// Hello Asha
// nobody
// backup
// [Asha]

Finished this page? Track your progress (saved only in your browser).