- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainNullCheck.java
More file actions
Latest commit
49 lines (41 loc) · 1.63 KB
/
Copy pathMainNullCheck.java
File metadata and controls
49 lines (41 loc) · 1.63 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
packageexamples;
importjava.util.Optional;
importjava.util.function.Supplier;
publicclassMainNullCheck {
publicstatic <T> Optional<T> resolve(Supplier<T> resolver) {
try {
Tresult = resolver.get();
returnOptional.ofNullable(result);
} catch (NullPointerExceptione) {
returnOptional.empty();
}
}
publicstaticvoidmain(String[] args) {
Outerouter = newOuter();
Outerobj = newOuter();
Nestednested = newNested();
Innerinner = newInner();
nested.setInner(inner);
outer.setNested(nested);
//traditional way
System.out.println("In the traditional check");
if (outer != null && outer.getNested() != null && outer.getNested().getInner() != null) {
System.out.println(outer.getNested().getInner().getFoo());
}
//Using java8 Optional type
// map accepts a lambda expression of type Function and wraps each function result into an Optional
// Null checks are automatically handled under the hood
System.out.println("In the Optional");
Optional.of(outer)
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
//Alternative way using Supplier function
System.out.println("Using Supplier function");
resolve(() -> outer.getNested().getInner().getFoo())
.ifPresent(System.out::println);
resolve(() -> obj.getNested().getInner().getFoo())
.ifPresent(System.out::println);
}
}