Sub topic 12
Newer Methods: or and stream
Java 9 added two small methods to Optional, called or and stream. Both help when you have more than one Optional to work with. or lets you try a backup source when the first one is empty. stream lets you mix Optionals into a stream pipeline.
You need Java 9 or later to run the code in this chapter.
Trying a Backup with or
Programs often look for a value in more than one place. For example, an app might check a fast cache first and then a slower database. A cache is a quick, temporary store of data.
You already know orElse. It gives back a plain value when the Optional is empty. Sometimes the backup is itself an Optional, though, because the database might not have the value either. That is the job of or.
The or method takes a Supplier. A Supplier is a small function that takes nothing and returns something. Here it must return an Optional. The rules are:
- If the first Optional has a value,
orreturns it unchanged. The Supplier never runs. - If the first Optional is empty,
orcalls the Supplier and returns the Optional it produces.
Because or returns an Optional, you can keep chaining. You can add another or, a map, or a final orElse.
import java.util.Optional;
public class OrDemo {
static Optional<String> fromCache() {
System.out.println("Checking cache...");
return Optional.empty();
}
static Optional<String> fromDatabase() {
System.out.println("Checking database...");
return Optional.of("db-value");
}
static Optional<String> fromFile() {
System.out.println("Checking file...");
return Optional.of("file-value");
}
public static void main(String[] args) {
String value = fromCache()
.or(OrDemo::fromDatabase)
.or(OrDemo::fromFile)
.orElse("default");
System.out.println(value);
}
}The output is:
Checking cache...
Checking database...
db-valueThe file is never checked. The database already returned a value, so the second or passed it along and did not call its Supplier.
| Method | Backup is | Returns |
|---|---|---|
| `orElse` | a plain value | a plain value |
| `or` | a Supplier of an Optional | an Optional |
Turning an Optional into a Stream
A stream is a sequence of items that you process step by step, such as filtering and collecting. The stream method turns an Optional into a stream:
- A full Optional becomes a stream with one item.
- An empty Optional becomes a stream with zero items.
This is useful when you have a list of Optionals and want only the real values. Pass Optional::stream to flatMap on the stream. Here flatMap means "turn each item into a small stream, then join them all together." Empty Optionals add nothing, so they drop out.
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class StreamMethodDemo {
static Optional<String> findNickname(String user) {
if (user.equals("ana")) return Optional.of("Annie");
if (user.equals("ben")) return Optional.of("Benny");
return Optional.empty();
}
public static void main(String[] args) {
List<String> users = List.of("ana", "carl", "ben", "dina");
List<String> nicknames = users.stream()
.map(StreamMethodDemo::findNickname)
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(nicknames); // [Annie, Benny]
}
}Before Java 9 you had to write .filter(Optional::isPresent).map(Optional::get) to do this. Optional::stream does the same thing in one step and never calls get.
Exercise
Optional<String> a = Optional.of("x"); What does a.or(() -> Optional.of("y")).orElse("z") return, and does the Supplier run?
Show answer
It returns "x". Because a already holds a value, or returns it unchanged and the Supplier is never called, so "y" is never created. orElse then has a value and returns "x".
Exercise
You have List<Optional<Integer>> nums = List.of(Optional.of(1), Optional.empty(), Optional.of(3)). Write a pipeline that prints the sum of the present values.
Show answer
System.out.println(nums.stream().flatMap(Optional::stream).mapToInt(Integer::intValue).sum()); prints 4. flatMap(Optional::stream) removes the empty Optional, and mapToInt followed by sum adds 1 and 3.