一、Optional类创建
Optional.empty()
Optional.of(T)
Optional.ofNullable(T)
二、常用方法
//get()-返回包装对象值,为空抛异常[不建议使用]
//java.util.NoSuchElementException: No value present
Student student = new Student();
Optional<Student> optionalStudent = Optional.ofNullable(student);
optionalStudent.get();
//isPresent()-判断对象是否为空[不建议使用]
optionalStudent.isPresent();
//ifPresent()-对象不为空时进行操作
optionalStudent.ifPresent(System.out::println);
//filter()-过滤
optionalStudent.filter(e->e.getAge()>10);
//map()-返回U类型
optionalStudent.map(e->e.getAge());
//flatMap-返回值类型为Optional<U>类型
optionalStudent.flatMap(e->Optional.ofNullable(e.getAge()));
//orElse()-如果包装对象值非空,返回包装对象值,否则返回入参other的值(默认值)
optionalStudent.map(e -> e.getAge()).orElse(250);
//orElseGet()-用Supplier对象的get()方法的返回值作为默认值
optionalStudent.map(e -> e.getAge()).orElseGet(() -> 251)
//orElseThrow()-用于包装对象值为空时需要抛出特定异常的场景
optionalStudent.map(e->e.getAge()).orElseThrow(()->new RuntimeException());
网友评论