Skip to content

Commit bbf7c93

Browse files
committed
Some is obsolete, can be replaced with Optional.map (see Optional2)
1 parent e2b0126 commit bbf7c93

File tree

3 files changed

+50
-130
lines changed

3 files changed

+50
-130
lines changed

src/com/winterbe/java8/Optional2.java

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,76 @@
11
package com.winterbe.java8;
22

33
import java.util.Optional;
4+
import java.util.function.Supplier;
45

56
/**
7+
* Examples how to avoid null checks with Optional:
8+
*
9+
* http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/
10+
*
611
* @author Benjamin Winterberg
712
*/
813
public class Optional2 {
914

1015
static class Outer {
11-
Nested nested;
16+
Nested nested = new Nested();
17+
18+
public Nested getNested() {
19+
return nested;
20+
}
1221
}
1322

1423
static class Nested {
15-
Inner inner;
24+
Inner inner = new Inner();
25+
26+
public Inner getInner() {
27+
return inner;
28+
}
1629
}
1730

1831
static class Inner {
19-
String foo;
32+
String foo = "boo";
33+
34+
public String getFoo() {
35+
return foo;
36+
}
2037
}
2138

2239
public static void main(String[] args) {
2340
test1();
41+
test2();
42+
test3();
43+
}
44+
45+
public static <T> Optional<T> resolve(Supplier<T> resolver) {
46+
try {
47+
T result = resolver.get();
48+
return Optional.ofNullable(result);
49+
}
50+
catch (NullPointerException e) {
51+
return Optional.empty();
52+
}
53+
}
54+
55+
private static void test3() {
56+
Outer outer = new Outer();
57+
resolve(() -> outer.getNested().getInner().getFoo())
58+
.ifPresent(System.out::println);
59+
}
60+
61+
private static void test2() {
62+
Optional.of(new Outer())
63+
.map(Outer::getNested)
64+
.map(Nested::getInner)
65+
.map(Inner::getFoo)
66+
.ifPresent(System.out::println);
2467
}
2568

2669
private static void test1() {
2770
Optional.of(new Outer())
28-
.flatMap(o -> Optional.ofNullable(o.nested))
29-
.flatMap(n -> Optional.ofNullable(n.inner))
30-
.flatMap(i -> Optional.ofNullable(i.foo))
31-
.ifPresent(System.out::println);
71+
.flatMap(o -> Optional.ofNullable(o.nested))
72+
.flatMap(n -> Optional.ofNullable(n.inner))
73+
.flatMap(i -> Optional.ofNullable(i.foo))
74+
.ifPresent(System.out::println);
3275
}
3376
}

src/com/winterbe/java8/Some.java

Lines changed: 0 additions & 61 deletions
This file was deleted.

src/com/winterbe/java8/SomeTest.java

Lines changed: 0 additions & 62 deletions
This file was deleted.

0 commit comments

Comments
 (0)