核心代码一
import entity.Student;
import java.util.Optional;
public class OptonalDemo {
public static void main(String[] args) throws Exception {
Student student = new Student();
Optional<Student> student1 = Optional.of(student);
Student student2 = null;
Optional<Student> opt = Optional.ofNullable(student2);
if(opt.isPresent()) {
System.out.println("optional 不为空");
Student student3 = opt.get();
} else {
System.out.println("optional 为空");
}
}
}
核心代码二
import entity.Student;
import java.util.Optional;
public class OrElseDemo {
public static void main(String[] args) throws Exception {
Student student = null;
Student student2 = new Student();
student2.setAge(10);
student2.setName("李洪伟");
Student student1 = Optional.ofNullable(student).orElse(student2);
System.out.println(student1);
Integer age = Optional.ofNullable(student2).map(obj -> obj.getAge()).orElse(7);
System.out.println("age1:" + age);
Integer age2 = Optional.ofNullable(student).map(obj -> obj.getAge()).orElse(7);
System.out.println("age1:" + age2);
}
}