forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptional2.java
More file actions
76 lines (63 loc) · 1.77 KB
/
Optional2.java
File metadata and controls
76 lines (63 loc) · 1.77 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.winterbe.java8.samples.stream;
import java.util.Optional;
import java.util.function.Supplier;
/**
* Examples how to avoid null checks with Optional:
*
* http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/
*
* @author Benjamin Winterberg
*/
public class Optional2 {
static class Outer {
Nested nested = new Nested();
public Nested getNested() {
return nested;
}
}
static class Nested {
Inner inner = new Inner();
public Inner getInner() {
return inner;
}
}
static class Inner {
String foo = "boo";
public String getFoo() {
return foo;
}
}
public static void main(String[] args) {
test1();
test2();
test3();
}
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
private static void test3() {
Outer outer = new Outer();
resolve(() -> outer.getNested().getInner().getFoo())
.ifPresent(System.out::println);
}
private static void test2() {
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
}
private static void test1() {
Optional.of(new Outer())
.flatMap(o -> Optional.ofNullable(o.nested))
.flatMap(n -> Optional.ofNullable(n.inner))
.flatMap(i -> Optional.ofNullable(i.foo))
.ifPresent(System.out::println);
}
}