Sub topic 3
Transforming and Filtering with map and filter
You can work with the value inside an Optional without taking it out first. Each method in this chapter returns a new Optional. If the Optional is empty, the method does nothing and passes the empty Optional along.
map and filter
map is a method that changes the value inside an Optional. filter is a method that keeps the value only if a test passes. If the test fails, you get an empty Optional.
import java.util.Optional;
public class MapFilterDemo {
public static void main(String[] args) {
int length = Optional.of(" hello ")
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(String::length)
.orElse(0);
System.out.println(length); // 5
}
}Chaining Lookups with flatMap
Some methods already return an Optional. If you pass one of them to map, you get Optional<Optional<Integer>>, which is awkward to use. flatMap avoids the nesting and gives you one flat Optional.
import java.util.Optional;
public class FlatMapDemo {
static Optional<Integer> parse(String s) {
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static void main(String[] args) {
int n = Optional.of("42").flatMap(FlatMapDemo::parse).orElse(-1);
System.out.println(n); // 42
}
}Streams, Primitive Optionals, or, and stream
Some stream methods, such as findFirst, return an Optional because the stream might be empty. Streams of numbers return a primitive Optional instead. A primitive Optional is a version made for plain numbers: OptionalInt, OptionalLong, or OptionalDouble.
Java 9 added two methods:
orgives you a backup Optional when the first one is empty.streamturns an Optional into a stream with zero or one item.
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class MoreDemo {
static Optional<String> fromCache() { return Optional.empty(); }
static Optional<String> fromDatabase() { return Optional.of("db-value"); }
public static void main(String[] args) {
Optional<String> firstB = List.of("Ana", "Bob").stream()
.filter(n -> n.startsWith("B"))
.findFirst();
System.out.println(firstB.orElse("none")); // Bob
OptionalInt max = IntStream.of(3, 9, 4).max();
System.out.println(max.orElse(-1)); // 9
String value = fromCache().or(MoreDemo::fromDatabase).orElse("default");
System.out.println(value); // db-value
List<String> present = List.of(Optional.of("a"), Optional.<String>empty())
.stream()
.flatMap(Optional::stream)
.toList();
System.out.println(present); // [a]
}
}Using Optional Well
| Do | Avoid |
|---|---|
| Return Optional from methods that might find nothing | Optional as a field in a class |
| Use `orElse`, `orElseGet`, `orElseThrow` | Calling `get` without a check |
| Return an empty list for "no results" | Optional as a method parameter |
| Return `Optional.empty()` | Returning `null` from an Optional method |
Exercise
A method findUser(id) returns Optional<User>, and user.email() returns Optional<String>. Should you use map or flatMap to get the email, and why?
Show answer
Use flatMap. email() already returns an Optional, so map would give Optional<Optional<String>>. flatMap gives a single Optional<String>.