Java新特性玩转JDK8之Optional类

DBC 704 0
of()——null 值作为参数传递进去,则会抛异常
Optional<Student> opt = Optional.of(user);
ofNullable()——如果对象即可能是 null 也可能是⾮ null,应该使⽤ ofNullable() ⽅法
Optional<Student> opt = Optional.ofNullable(user);
访问 Optional 对象的值——get() ⽅法
Optional<Student> opt = Optional.ofNullable(student);
Student s = opt.get();
如果值存在则isPresent()⽅法会返回true,调⽤get()⽅法会返回该对象⼀般使⽤get之前需要
先验证是否有值,不然还会报错
public static void main(String[] args) {
 Student student = null;
 test(student);
}
public static void test(Student student){
 Optional<Student> opt = Optional.ofNullable(student);
 System.out.println(opt.isPresent());
}
兜底 orElse⽅法——orElse()如果有值则返回该值,否则返回传递给它的参数值
Student student1 = null;
Student student2 = new Student(2);
Student result = Optional.ofNullable(student1).orElse(student2);
System.out.println(result.getAge());

Student student = null;
int result = Optional.ofNullable(student).map(obj-
>obj.getAge()).orElse(4);
System.out.println(result);

发表评论 取消回复
表情 图片 链接 代码

分享