File tree Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Original file line number Diff line number Diff line change 22
33import java .util .Optional ;
44import java .util .function .Function ;
5+ import java .util .function .Supplier ;
56
67/**
78 * Simplified elvis-like operator. You can achieve the same with Optional but Take has simpler syntax.
@@ -19,15 +20,25 @@ private Take(T value) {
1920 this .value = value ;
2021 }
2122
23+ public static <T > Optional <T > of (Supplier <T > resolver ) {
24+ try {
25+ T result = resolver .get ();
26+ return Optional .ofNullable (result );
27+ }
28+ catch (NullPointerException e ) {
29+ return Optional .empty ();
30+ }
31+ }
32+
2233 public static <T > Take <T > of (T something ) {
2334 return new Take <>(something );
2435 }
2536
26- public <S > Take <S > take (Function <? super T , S > mapper ) {
37+ public <S > Take <S > take (Function <? super T , S > resolver ) {
2738 if (!isPresent ()) {
2839 return empty ();
2940 }
30- S result = mapper .apply (value );
41+ S result = resolver .apply (value );
3142 return new Take <>(result );
3243 }
3344
Original file line number Diff line number Diff line change @@ -40,7 +40,21 @@ public static void main(String[] args) {
4040 .take (Inner ::getFoo )
4141 .get ();
4242
43- System .out .println (optional .get ());
43+ System .out .println (optional .isPresent ());
44+
45+ something .getNested ().inner = null ;
46+ Optional <String > optional2 = Take .of (() ->
47+ something .getNested ().getInner ().getFoo ());
48+ System .out .println (optional2 .isPresent ());
49+
50+
51+ String x = null ;
52+ String y = "boo" ;
53+ String z = Take .of (x ).orElse (y );
54+
55+ System .out .println (z );
56+
57+
4458 }
4559
4660}
You can’t perform that action at this time.
0 commit comments