|
1 | 1 | package com.winterbe.java8;
|
2 | 2 |
|
3 | 3 | import java.util.Optional;
|
| 4 | +import java.util.function.Supplier; |
4 | 5 |
|
5 | 6 | /**
|
| 7 | + * Examples how to avoid null checks with Optional: |
| 8 | + * |
| 9 | + * http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/ |
| 10 | + * |
6 | 11 | * @author Benjamin Winterberg
|
7 | 12 | */
|
8 | 13 | public class Optional2 {
|
9 | 14 |
|
10 | 15 | static class Outer {
|
11 |
| - Nested nested; |
| 16 | + Nested nested = new Nested(); |
| 17 | + |
| 18 | + public Nested getNested() { |
| 19 | + return nested; |
| 20 | + } |
12 | 21 | }
|
13 | 22 |
|
14 | 23 | static class Nested {
|
15 |
| - Inner inner; |
| 24 | + Inner inner = new Inner(); |
| 25 | + |
| 26 | + public Inner getInner() { |
| 27 | + return inner; |
| 28 | + } |
16 | 29 | }
|
17 | 30 |
|
18 | 31 | static class Inner {
|
19 |
| - String foo; |
| 32 | + String foo = "boo"; |
| 33 | + |
| 34 | + public String getFoo() { |
| 35 | + return foo; |
| 36 | + } |
20 | 37 | }
|
21 | 38 |
|
22 | 39 | public static void main(String[] args) {
|
23 | 40 | 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); |
24 | 67 | }
|
25 | 68 |
|
26 | 69 | private static void test1() {
|
27 | 70 | 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); |
32 | 75 | }
|
33 | 76 | }
|
0 commit comments