Sub topic 8
Transforming and Filtering with map and filter
So far you have put values into an Optional and taken them out again. Often you want to change the value inside first, or check it against a rule. You could unpack the value, work on it, and wrap it again. The map and filter methods do this for you in one step, and they never touch a missing value.
What map does
map is a method that applies a function to the value inside an Optional. A function here is a lambda or method reference that takes one value and returns another.
- If the Optional holds a value,
mapruns the function and wraps the result in a new Optional. - If the Optional is empty,
mapskips the function and returns an empty Optional.
So you never need to check for presence before calling map.
import java.util.Optional;
public class MapDemo {
public static void main(String[] args) {
Optional<String> name = Optional.of("ada");
Optional<String> upper = name.map(String::toUpperCase);
System.out.println(upper.orElse("none")); // ADA
Optional<String> missing = Optional.empty();
Optional<String> stillMissing = missing.map(String::toUpperCase);
System.out.println(stillMissing.orElse("none")); // none
}
}The type inside can change. Mapping an Optional<String> with String::length gives an Optional<Integer>.
What filter does
filter keeps the value only if it passes a test. The test is a predicate, which is a function that returns true or false.
- If the value passes the test,
filterreturns the same Optional. - If the value fails the test,
filterreturns an empty Optional. - If the Optional is already empty, it stays empty.
import java.util.Optional;
public class FilterDemo {
public static void main(String[] args) {
Optional<Integer> age = Optional.of(15);
Optional<Integer> adult = age.filter(a -> a >= 18);
System.out.println(adult.isPresent()); // false
Optional<Integer> teen = age.filter(a -> a >= 13);
System.out.println(teen.isPresent()); // true
}
}Building a chain
The real benefit shows when you join these calls together. Each call returns an Optional, so you can call the next method directly on it. You finish the chain with a retrieval method such as orElse.
Here is a worked example. You get some user input that might contain extra spaces. You want its length after trimming, but only if it is not blank.
import java.util.Optional;
public class MapFilterDemo {
public static void main(String[] args) {
Optional<String> input = Optional.of(" hello ");
int length = input
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(String::length)
.orElse(0);
System.out.println(length); // 5
}
}Step by step:
map(String::trim)turns" hello "into"hello".filter(s -> !s.isEmpty())checks that"hello"is not empty. It passes.map(String::length)turns"hello"into5.orElse(0)takes out5.
If the input were " ", trimming would give "". The filter would fail, the Optional would become empty, and the last map would be skipped. orElse(0) would then return 0.
Common mistakes
| Mistake | Better approach |
|---|---|
| Calling `isPresent()` then `get()` before transforming | Call `map` directly. It handles the empty case. |
| Using `filter` to change the value | `filter` only keeps or drops the value. Use `map` to change it. |
| Forgetting to end the chain | The result is still an Optional. Finish with `orElse`, `orElseGet`, or `orElseThrow`. |
| Passing a function that returns an Optional to `map` | You get a nested Optional. The next chapter shows how `flatMap` fixes this. |
Exercise
What does this code print? Optional.of("Java").map(String::toLowerCase).filter(s -> s.startsWith("p")).orElse("no match")
Show answer
It prints "no match". The map step turns "Java" into "java". "java" does not start with "p", so filter returns an empty Optional, and orElse supplies "no match".
Exercise
Write one chain that takes an Optional<String> called word and returns its length if the word has more than 3 characters, or -1 otherwise.
Show answer
int result = word.filter(w -> w.length() > 3).map(String::length).orElse(-1); You could also map to the length first and then filter with n -> n > 3.