-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionalIsEmpty.java
More file actions
74 lines (57 loc) · 2.29 KB
/
Copy pathOptionalIsEmpty.java
File metadata and controls
74 lines (57 loc) · 2.29 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package java11.optional;
import java.util.Optional;
/**
* Java 11 Optional.isEmpty() Method
* Demonstrates the isEmpty() method for checking empty Optionals
*/
public class OptionalIsEmpty {
public static void main(String[] args) {
// 1. isEmpty() - More readable than !isPresent()
System.out.println("=== isEmpty() Examples ===");
Optional<String> optional1 = Optional.of("Value");
Optional<String> optional2 = Optional.empty();
System.out.println("optional1.isEmpty(): " + optional1.isEmpty()); // false
System.out.println("optional2.isEmpty(): " + optional2.isEmpty()); // true
// 2. Comparison with isPresent()
System.out.println("\n=== Comparison ===");
Optional<String> name = findName(123);
// Old way (before Java 11)
if (!name.isPresent()) {
System.out.println("Name not found (old way)");
}
// New way (Java 11) - more readable
if (name.isEmpty()) {
System.out.println("Name not found (new way)");
}
// 3. Practical example
System.out.println("\n=== Practical Example ===");
Optional<String> config = getConfiguration("app.name");
if (config.isEmpty()) {
System.out.println("Configuration not found, using default");
config = Optional.of("DefaultApp");
}
System.out.println("App name: " + config.get());
// 4. Chain with orElse
System.out.println("\n=== Chaining ===");
Optional<String> value = Optional.empty();
if (value.isEmpty()) {
value = Optional.of("Default");
}
System.out.println("Value: " + value.get());
// Or more concisely
String result = value.orElse("Fallback");
System.out.println("Result: " + result);
}
private static Optional<String> findName(int id) {
if (id == 123) {
return Optional.of("John Doe");
}
return Optional.empty();
}
private static Optional<String> getConfiguration(String key) {
if ("app.name".equals(key)) {
return Optional.of("MyApplication");
}
return Optional.empty();
}
}