Sub topic 12
Newer Methods: or and stream
Java 9 added two useful methods to Optional. The or method lets you try a backup source when a value is missing. The stream method turns an Optional into a stream so it fits into stream pipelines. This chapter covers both methods, shows how each behaves, and points out the mistakes beginners often make with them.
Both methods need Java 9 or later. If you run the examples on Java 8, they will not compile.
A Quick Reminder
An Optional is a box that holds one value or nothing. A box with a value is called "present." An empty box is called "empty."
You already know methods like orElse, which take a value out of the box or give you a default. The two methods in this chapter work a little differently. Neither one takes the value out of the box. Each one gives you back another container: or returns an Optional, and stream returns a Stream.
The or Method: Trying a Backup Source
The problem it solves
Programs often look for data in more than one place. Say your app wants a user's favorite color:
- First, check a fast memory store, called a cache.
- If the cache has nothing, check the database.
- If the database has nothing, use a default.
Each lookup might find nothing, so each one returns an Optional. You need a clean way to say "if this one is empty, try that one."
What or does
or is a method that takes a Supplier. A Supplier is a small function that takes no input and returns something. Here, the Supplier must return another Optional.
The rules are simple:
- If the first
Optionalis present,orreturns it unchanged. The Supplier is never called. - If the first
Optionalis empty,orcalls the Supplier and returns theOptionalit produces.
The result is always an Optional. You can then call or again, or finish with a method like orElse.
A worked example
This program checks a cache first and then a database. The print statements show which lookups actually run.
import java.util.Optional;
public class OrDemo {
static Optional<String> fromCache(String key) {
System.out.println("Checking cache...");
return Optional.empty();
}
static Optional<String> fromDatabase(String key) {
System.out.println("Checking database...");
if (key.equals("color")) {
return Optional.of("blue");
}
return Optional.empty();
}
public static void main(String[] args) {
String color = fromCache("color")
.or(() -> fromDatabase("color"))
.orElse("default");
System.out.println("Result: " + color);
String size = fromCache("size")
.or(() -> fromDatabase("size"))
.orElse("medium");
System.out.println("Result: " + size);
}
}The output is:
Checking cache...
Checking database...
Result: blue
Checking cache...
Checking database...
Result: mediumHere is what happens step by step:
fromCache("color")returns an emptyOptional.- Because it is empty,
orcalls the lambda, which runsfromDatabase("color"). - The database returns
Optional.of("blue"). orElse("default")sees a present value and returns"blue".
For "size", both lookups come back empty, so orElse supplies "medium".
or is lazy
"Lazy" means the work is done only when it is needed. or is lazy because it calls the Supplier only when the first Optional is empty. This matters when the backup is slow, such as a database query or a network call.
import java.util.Optional;
public class OrLazyDemo {
static Optional<String> slowLookup() {
System.out.println("Slow lookup ran!");
return Optional.of("backup");
}
public static void main(String[] args) {
Optional<String> result = Optional.of("first")
.or(OrLazyDemo::slowLookup);
System.out.println(result.get());
}
}The output is only:
firstThe slow lookup never ran, because the first Optional already had a value.
Chaining several sources
You can chain as many or calls as you need. Java tries them from left to right and stops at the first present value.
import java.util.Optional;
public class OrChainDemo {
static Optional<String> fromCache() { return Optional.empty(); }
static Optional<String> fromDatabase() { return Optional.empty(); }
static Optional<String> fromConfigFile() { return Optional.of("from-config"); }
public static void main(String[] args) {
String value = fromCache()
.or(OrChainDemo::fromDatabase)
.or(OrChainDemo::fromConfigFile)
.orElse("hard-coded default");
System.out.println(value); // from-config
}
}This reads almost like a sentence: "from the cache, or the database, or the config file, or else a default."
or compared with orElse and orElseGet
These three methods look alike, but they return different things.
| Method | What you pass in | What it returns | When is the backup computed? |
|---|---|---|---|
| `orElse(value)` | A plain value | The value itself (`T`) | Always, before the call |
| `orElseGet(supplier)` | A Supplier of a value | The value itself (`T`) | Only when empty |
| `or(supplier)` | A Supplier of an `Optional` | An `Optional<T>` | Only when empty |
Use or when the backup might also be missing. Use orElse or orElseGet when you are ready to leave the Optional and get a real value.
Edge cases with or
- The Supplier must not return
null. It must return anOptional, even an empty one. If it returnsnull,orthrows aNullPointerException. ReturnOptional.empty()instead. - The Supplier itself must not be
null. Callingor(null)throws aNullPointerException, even when the firstOptionalis present. - Types must match. If you start with
Optional<String>, the Supplier must give back anOptionalofString(or a subtype ofString).
The stream Method: Optional as a Tiny Stream
What it does
A stream is a sequence of items that you can process step by step, for example with filter and map. The stream method turns an Optional into a stream:
- A present
Optionalbecomes a stream with one item. - An empty
Optionalbecomes a stream with zero items.
import java.util.Optional;
public class OptionalStreamBasics {
public static void main(String[] args) {
long a = Optional.of("hi").stream().count();
long b = Optional.<String>empty().stream().count();
System.out.println(a); // 1
System.out.println(b); // 0
}
}On its own this looks small. Its real use is inside bigger stream pipelines.
The main use: dropping empty results
Imagine you have a list of user IDs. For each ID, a lookup returns an Optional<String> with that user's email. Some users have no email. You want a list of only the emails that exist.
If you use map, you get a stream of Optional<String> values, some of them empty. You want plain strings with the empties removed. The method flatMap on a stream helps here. flatMap replaces each item with a small stream and then joins all those small streams into one. Pair it with Optional::stream, and each present value becomes one item while each empty value becomes nothing.
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class EmailDemo {
static final Map<String, String> EMAILS = Map.of(
"u1", "[email protected]",
"u3", "[email protected]");
static Optional<String> findEmail(String id) {
return Optional.ofNullable(EMAILS.get(id));
}
public static void main(String[] args) {
List<String> ids = List.of("u1", "u2", "u3");
List<String> emails = ids.stream()
.map(EmailDemo::findEmail) // Stream<Optional<String>>
.flatMap(Optional::stream) // Stream<String>, empties dropped
.collect(Collectors.toList());
System.out.println(emails); // [[email protected], [email protected]]
}
}User "u2" has no email. Its empty Optional turns into an empty stream, so it disappears from the result.
The old way, before Java 9
Before Java 9, people wrote this:
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class OldWayDemo {
public static void main(String[] args) {
List<Optional<String>> items = List.of(
Optional.of("a"), Optional.empty(), Optional.of("c"));
List<String> present = items.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
System.out.println(present); // [a, c]
}
}This works, but it takes two steps and uses get, which earlier chapters warned against. flatMap(Optional::stream) does the same job in one step with no get call.
Using stream to reach stream methods
Sometimes you want a stream method that Optional does not have. Converting with stream() gives you access to all of them. For example, you can join an Optional value onto another stream:
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ConcatDemo {
public static void main(String[] args) {
Optional<String> middleName = Optional.empty();
String full = Stream.concat(
Stream.of("Ada"),
Stream.concat(middleName.stream(), Stream.of("Lovelace")))
.collect(Collectors.joining(" "));
System.out.println(full); // Ada Lovelace
}
}If middleName held "King", the result would be "Ada King Lovelace". You don't need an if statement.
Edge cases with stream
- Primitive Optionals have it too.
OptionalInt,OptionalLong, andOptionalDoubleeach have astream()method. They returnIntStream,LongStream, andDoubleStream. - Don't wrap a single value just to unwrap it. If you only need the value or a default,
orElseis simpler thanstream(). Usestream()when you are already working with streams. - On Java 16 and later, you can write
.toList()instead of.collect(Collectors.toList()). The list it returns cannot be changed.
Other Small Additions in Java 10 and 11
Two more methods arrived soon after Java 9. Earlier chapters showed how to use them. This table lists when each one was added:
| Method | Added in | What it does |
|---|---|---|
| `or(supplier)` | Java 9 | Returns a backup `Optional` when empty |
| `stream()` | Java 9 | Turns the `Optional` into a stream of 0 or 1 items |
| `ifPresentOrElse(action, emptyAction)` | Java 9 | Runs one action or the other |
| `orElseThrow()` (no arguments) | Java 10 | Like `get`, but its name makes the risk clear |
| `isEmpty()` | Java 11 | The opposite of `isPresent` |
Summary
orreturns the firstOptionalif it is present. If it is empty,orcalls a Supplier and returns itsOptional. The Supplier runs only when needed.- Chain
orcalls to try several sources, and end the chain withorElse,orElseGet, ororElseThrow. streamturns anOptionalinto a stream of zero or one items.flatMap(Optional::stream)removes emptyOptionalvalues from a stream and unwraps the present ones.
Exercise
What does this code print, and does "B ran" appear in the output? Optional<String> r = Optional.of("A").or(() -> { System.out.println("B ran"); return Optional.of("B"); }); System.out.println(r.get());
Show answer
It prints only "A". "B ran" does not appear, because or calls its Supplier only when the first Optional is empty. Here the first Optional already holds "A".
Exercise
You have a List<Optional<Integer>> holding Optional.of(4), Optional.empty(), and Optional.of(7). Write one stream pipeline that adds up only the present numbers.
Show answer
list.stream().flatMap(Optional::stream).mapToInt(Integer::intValue).sum() returns 11. flatMap(Optional::stream) drops the empty Optional and unwraps the others, and mapToInt with sum adds 4 and 7.
Exercise
A teammate writes fromCache().or(() -> null).orElse("x"), and the cache is empty. What happens, and how should they fix it?
Show answer
It throws a NullPointerException, because the Supplier given to or must return an Optional, not null. The fix is to return Optional.empty() from the Supplier, or to drop the or call and use orElse("x") directly.