-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOptionalDemo.java
More file actions
37 lines (27 loc) · 819 Bytes
/
OptionalDemo.java
File metadata and controls
37 lines (27 loc) · 819 Bytes
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
package com.diyishuai.java8.optional;
import com.diyishuai.java8.Student;
import java.util.Optional;
/**
* @author Shea
* @date 2021-01-20
* @description
*/
public class OptionalDemo {
private static boolean isNull = false;
public static void main(String[] args) {
String id = "666";
//1.7
Student student = getById(id);
if (student != null) {
System.out.println("if : name -> " + student.getName());
}
//1.8
Optional<Student> studentOpt = Optional.ofNullable(getById(id));
studentOpt.ifPresent(s ->
System.out.println("opt : name -> " + s.getName())
);
}
private static Student getById(String id) {
return isNull ? null : new Student().setId(id).setName(id + " student");
}
}