-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionl class
More file actions
36 lines (26 loc) · 1.04 KB
/
Copy pathOptionl class
File metadata and controls
36 lines (26 loc) · 1.04 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
import java.util.Optional;
public class Main {
public static void main(String[] args) {
// use only one 1, 2, or 3 as per requirement:
// 1. of() -> value must not be null
Optional<String> op1 = Optional.of("Yogesh");
// 2. empty() -> no value
Optional<String> op2 = Optional.empty();
// 3. ofNullable() -> null allowed
Optional<String> op3 = Optional.ofNullable(null);
// -----------------------------------
// isPresent()
System.out.println("isPresent: " + op1.isPresent());
// get()
System.out.println("get: " + op1.get());
// orElse()
System.out.println("orElse: " + op3.orElse("Default Name"));
// ifPresent()
op1.ifPresent(name -> System.out.println("ifPresent: " + name));
// orElseThrow()
System.out.println("orElseThrow: " + op1.orElseThrow());
// -----------------------------------
// empty optional example
System.out.println("Empty value: " + op2.orElse("No Data"));
}
}