File tree Expand file tree Collapse file tree 1 file changed +10
-2
lines changed
src/main/java/com/test/optional Expand file tree Collapse file tree 1 file changed +10
-2
lines changed Original file line number Diff line number Diff line change @@ -8,15 +8,18 @@ public static void main(String[] args) {
88
99 A objA = new A (1 , "Arpit" );
1010 Optional <A > optional = Optional .ofNullable (objA );
11- System .out .println (optional .map (e -> new B (e .getId (), e .getName ())).get ());
11+ System .out .println (optional .map (e -> new B (e .getId (), e .getName ()))
12+ .orElse (new B ())); // Output : B [id=1, name=Arpit]
1213
1314 Optional <A > optionalOfNull = Optional .ofNullable (null );
1415
15- System .out .println (optionalOfNull .map (e -> new B (e .getId (), e .getName ())));
16+ System .out .println (optionalOfNull .map (
17+ e -> new B (e .getId (), e .getName ())).orElse (new B ())); // Output : B [id=0, name=null]
1618 }
1719}
1820
1921class A {
22+
2023 private int id ;
2124 private String name ;
2225
@@ -48,9 +51,14 @@ public String toString() {
4851}
4952
5053class B {
54+
5155 private int id ;
5256 private String name ;
5357
58+ public B () {
59+
60+ }
61+
5462 public B (int id , String name ) {
5563 this .id = id ;
5664 this .name = name ;
You can’t perform that action at this time.
0 commit comments