- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionalExample.java
More file actions
Latest commit
53 lines (41 loc) · 1.64 KB
/
Copy pathOptionalExample.java
File metadata and controls
53 lines (41 loc) · 1.64 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
packagecom.learn.optional;
importcom.learn.data.Student;
importcom.learn.data.StudentDataBase;
importjava.util.Optional;
publicclassOptionalExample {
publicstaticvoidmain(String[] args) {
StringstudentName = getStudentName();
if (studentName != null) {
System.out.println("Length of Student Name " + studentName.length());
}else {
System.out.println("Name not found.");
}
Optional<String> studentNameOptional = getStudentNameOptional();
if (studentNameOptional.isPresent()) {
System.out.println("Length of Student Name Optional : " + studentNameOptional.get().length()); // to get actual value inside Optional.
}else {
System.out.println("Name not found.");
}
}
/**
* Too many null Checks.
* @return
*/
publicstaticStringgetStudentName() {
Studentstudent = StudentDataBase.studentSupplier.get();
// if student == null, then it return null
if (student == null) {
returnnull;
}
returnstudent.getName();
}
publicstaticOptional<String> getStudentNameOptional() {
// wrapping actual Student Object within Optional
Optional<Student> studentOptional = Optional.ofNullable(StudentDataBase.studentSupplier.get());
// Checks whether is this Optional Object has any value inside that object or not.
if (studentOptional.isPresent()) {
returnstudentOptional.map(Student::getName); // this return Optional<String>
}
returnOptional.empty(); // Represents an Optional Object with no value.
}
}