Sub topic 8
Transforming and Filtering with map and filter
In the last chapters you learned how to get a value out of an Optional safely. Often, though, you don't want the value exactly as it is. You might want to trim it, change it to uppercase, or turn a name into its length. Sometimes you only want to keep the value if it passes a test.
This chapter covers two methods for that work: map and filter. Both let you change or check the value while it is still inside the Optional. You never have to ask "is it there?" yourself. The Optional handles the empty case for you.
Why Not Just Unwrap First?
Here is code that does not use map or filter. It takes a name that may be missing and turns it into an uppercase greeting.
import java.util.Optional;
public class UnwrapFirstDemo {
public static void main(String[] args) {
Optional<String> name = Optional.of("ada");
String greeting;
if (name.isPresent()) {
String upper = name.get().toUpperCase();
greeting = "Hello, " + upper;
} else {
greeting = "Hello, guest";
}
System.out.println(greeting); // Hello, ADA
}
}This works, but it has problems:
- You must remember to check
isPresentbefore everyget. - The real work (uppercase, then add "Hello") is buried inside an
if. - Each new step adds more code to the
ifblock.
With map, the same logic is one short chain:
import java.util.Optional;
public class MapFirstDemo {
public static void main(String[] args) {
Optional<String> name = Optional.of("ada");
String greeting = name
.map(String::toUpperCase)
.map(n -> "Hello, " + n)
.orElse("Hello, guest");
System.out.println(greeting); // Hello, ADA
}
}There is no if and no get, and the steps read from top to bottom in the order they happen.
What map Does
map is a method that applies a function to the value inside an Optional and wraps the result in a new Optional.
A function here means a small piece of code that takes one input and gives back one output. In Java this is the Function<T, R> type. You usually write it as a lambda, like s -> s.length(), or a method reference, like String::length.
map follows two rules:
- If the Optional has a value,
mapcalls your function with that value and returns a new Optional holding the result. - If the Optional is empty,
mapdoes not call your function at all. It just returns an empty Optional.
The type can change along the way. If you start with Optional<String> and map with String::length, you get Optional<Integer>.
import java.util.Optional;
public class MapTypeDemo {
public static void main(String[] args) {
Optional<String> word = Optional.of("banana");
Optional<Integer> size = word.map(String::length);
System.out.println(size); // Optional[6]
Optional<String> missing = Optional.empty();
Optional<Integer> noSize = missing.map(String::length);
System.out.println(noSize); // Optional.empty
}
}When you print an Optional, Java shows Optional[value] for a full one and Optional.empty for an empty one. This is handy for checking your results while you learn.
Proof That the Function Is Skipped
You can see that map really skips your function on an empty Optional. Put a print statement inside the lambda:
import java.util.Optional;
public class MapSkipDemo {
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
Optional<Integer> result = empty.map(s -> {
System.out.println("map ran");
return s.length();
});
System.out.println(result); // Optional.empty
}
}The program prints only Optional.empty. The line "map ran" never appears. This also means your function can never receive null from map, so you don't need a null check inside it.
When Your Function Returns null
What if the function itself returns null? map handles that too. It turns a null result into an empty Optional.
import java.util.Map;
import java.util.Optional;
public class MapNullDemo {
static final Map<String, String> NICKNAMES = Map.of("Robert", "Bob");
public static void main(String[] args) {
Optional<String> nick1 = Optional.of("Robert").map(NICKNAMES::get);
Optional<String> nick2 = Optional.of("Alice").map(NICKNAMES::get);
System.out.println(nick1); // Optional[Bob]
System.out.println(nick2); // Optional.empty
}
}NICKNAMES.get("Alice") returns null, because there is no such key. map notices the null and gives back Optional.empty. It acts as if it called Optional.ofNullable on your result. This makes map a safe way to call older methods that return null.
What filter Does
filter is a method that keeps the value only if it passes a test. If the test fails, you get an empty Optional.
The test is a predicate. A predicate is a function that takes a value and returns true or false. In Java this is the Predicate<T> type, for example n -> n > 0.
filter follows three rules:
- If the Optional has a value and the test returns
true, you get the same Optional back. - If the Optional has a value and the test returns
false, you get an empty Optional. - If the Optional is empty, the test is not run, and you get an empty Optional.
Unlike map, filter never changes the value or its type. An Optional<Integer> stays an Optional<Integer>.
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);
Optional<Integer> teen = age.filter(a -> a >= 13 && a <= 19);
System.out.println(adult); // Optional.empty
System.out.println(teen); // Optional[15]
String message = age
.filter(a -> a >= 18)
.map(a -> "Welcome!")
.orElse("Sorry, adults only.");
System.out.println(message); // Sorry, adults only.
}
}A useful way to picture this: filter turns "a value that is not good enough" into "no value." The rest of the chain then treats it as missing.
Chaining map and filter Together
You can link map and filter into a chain, which is a series of method calls joined by dots. Each call works on the result of the one before it. If any step produces an empty Optional, every step after it is skipped until you reach orElse (or another way of getting the value out).
Here is a full example. It takes some text, trims the spaces, throws it away if it is blank, and returns its length.
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:
| Step | Call | Result |
|---|---|---|
| Start | `Optional.of(" hello ")` | `Optional[" hello "]` |
| 1 | `.map(String::trim)` | `Optional["hello"]` |
| 2 | `.filter(s -> !s.isEmpty())` | `Optional["hello"]` (test passed) |
| 3 | `.map(String::length)` | `Optional[5]` |
| 4 | `.orElse(0)` | `5` |
Now imagine the input was " " (only spaces). After step 1 it becomes "". The filter in step 2 fails, so the Optional becomes empty. Step 3 is skipped, and orElse(0) returns 0.
Order Matters
The order of steps changes the answer. Compare these two chains on the same input:
import java.util.Optional;
public class OrderDemo {
public static void main(String[] args) {
Optional<String> input = Optional.of(" ");
boolean trimThenCheck = input
.map(String::trim)
.filter(s -> !s.isEmpty())
.isPresent();
boolean checkThenTrim = input
.filter(s -> !s.isEmpty())
.map(String::trim)
.isPresent();
System.out.println(trimThenCheck); // false
System.out.println(checkThenTrim); // true
}
}In the second chain, the filter sees " ", which is not empty (it has three spaces), so it passes. Only then is it trimmed to "". The result is an Optional holding an empty string, which is probably not what you wanted. Always ask yourself: "what does the value look like at this step?"
Common Mistakes
Calling get Inside the Chain
Beginners sometimes write opt.map(...).get(). This brings back the danger you were trying to avoid. If the Optional is empty, get throws NoSuchElementException. End your chains with orElse, orElseGet, orElseThrow, or ifPresent instead.
Using map for Side Effects
A side effect is something a piece of code does besides returning a value, such as printing or saving to a file. map is meant to produce a new value. If you only want to do something with the value, use ifPresent, which you met in an earlier chapter.
import java.util.Optional;
public class SideEffectDemo {
public static void main(String[] args) {
Optional<String> user = Optional.of("grace");
// Clear: ifPresent is made for actions
user.ifPresent(u -> System.out.println("Logged in: " + u));
}
}Mapping to Another Optional
Sometimes your function already returns an Optional, such as a method findAddress(customer) that returns Optional<Address>. If you use map with it, you end up with Optional<Optional<Address>>, a box inside a box. That is awkward to work with. The next chapter shows how flatMap solves this.
Quick Reference
| Method | Takes | Value present | Value empty | Can change type? |
|---|---|---|---|---|
| `map` | `Function<T, R>` | Applies function, wraps result (null becomes empty) | Returns empty, function not called | Yes |
| `filter` | `Predicate<T>` | Keeps value if test is true, else empty | Returns empty, test not called | No |
Exercise
What does this code print? Optional<String> s = Optional.of("Java"); System.out.println(s.map(String::length).filter(n -> n > 5).orElse(-1));
Show answer
It prints -1. map turns "Java" into 4, giving Optional[4]. The filter test 4 > 5 is false, so the Optional becomes empty, and orElse returns -1.
Exercise
Write a chain that takes an Optional<String> email, keeps it only if it contains "@", converts it to lowercase, and returns "invalid" if anything is missing. Use map, filter, and orElse.
Show answer
String result = email.filter(e -> e.contains("@")).map(String::toLowerCase).orElse("invalid"); For Optional.of("[email protected]") this returns "[email protected]"; for Optional.of("nope") or Optional.empty() it returns "invalid".
Exercise
A Map<String, Integer> called prices has no key "tea". What is the result of Optional.of("tea").map(prices::get), and why does no exception occur?
Show answer
The result is Optional.empty. prices.get("tea") returns null, and map turns a null result into an empty Optional instead of throwing an exception.