Optional容器类的常用方法:
1. optional.of(T t) :创建一个Optional实例
Optional<Employee> op = Optional.of(new Employee());
Employee emp = op.get();
// 会在null处直接发生空指针异常
Optional.of(null);
2. Optional.empty() :创建一个空的Optional实例
Optional<Employee> op = Optional.empty();
// 会发生空指针异常
System.out.println(op.get());
3. Optional.ofNullable(T t) :若 t 不为null,创建Optional实例,否则创建空实例
Optional<Employee> op = Optional.ofNullable(new Employee);
System.out.println(op.get());
Optional<Employee> op = Optional.ofNullable(null);
// op.get()会发生空指针
System.out.println(op.get());
4. isPresent() :判断是否包含值
Optional<Employee> op = Optional.ofNullable(null);
if(isPresent()) {
System.out.println(op.get());
}
5. orElse(T t) :如果调用对象包含值,返回该值,否则返回t
Optional<Employee> op = Optional.ofNullable(null);
Employee emp = op.orElse(new Employee());
6. orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回s获取的值
Optional<Employee> op = Optional.ofNullable(null);
// 参数是函数式接口 可以写想要的逻辑
Employee emp = op.orElseGet(e -> new Employee());
7. map(Function f) :如果有值对其处理,并返回处理后的Optional,否则返回Optional.empty()
Optional<Employee> op = Optional.ofNullable(new Employee());
Optional<String> str = op.map(e -> e.getName());
8. flatMap(Function mapper) :与map类似,要求返回值必须是Optional
Optional<Employee> op = Optional.ofNullable(new Employee());
// flatMap返回值必须 用Optional包装一下
Optional<String> str = op.flatMap(e -> Optional.of(e.getName()));
System.out.println(str.get());