Skip to content

Commit 229e3f1

Browse files
committed
Optional followed with map operation
1 parent 117d455 commit 229e3f1

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/main/java/com/test/optional/OptionalOfNullableExample.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff 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

1921
class A {
22+
2023
private int id;
2124
private String name;
2225

@@ -48,9 +51,14 @@ public String toString() {
4851
}
4952

5053
class 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;

0 commit comments

Comments
 (0)