forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionalMapOf.java
More file actions
25 lines (17 loc) · 759 Bytes
/
OptionalMapOf.java
File metadata and controls
25 lines (17 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.zetcode;
import java.util.Optional;
import java.util.function.Function;
// if the result is already an Optional flatMap
// does not wrap it within an additional Optional
public class OptionalMapOf {
public static void main(String[] args) {
Function<String, Optional<String>> upperCase
= s -> (s == null) ? Optional.empty() : Optional.of(s.toUpperCase());
Optional<String> word = Optional.of("falcon");
Optional<Optional<String>> opt1 = word.map(upperCase);
Optional<String> opt2 = word.flatMap(upperCase);
opt1.ifPresent(s -> s.ifPresent(System.out::println));
opt2.ifPresentOrElse(System.out::println,
() -> System.out.println("Invalid value"));
}
}