JAVA8 新特性实际使用总结(一)
Optional
public final class Optional
extends ObjectA container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
容器对象,可能包含或不包含非空值。如果存在一个值,isPresent()将返回true并 get()返回值。
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).
还提供了依赖于包含值是否存在的其他方法,例如orElse() (如果值不存在,则返回一个默认值)以及ifPresent()(如果值存在,则 执行一个代码块)。
This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.
这是一个基于值的类; 应该慎用相等操作(包括==,hahcode 或 synchronization) Optional可能会产生不可预知的结果,应予以避免。
个人理解
Optional实际上是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
常规用法
Integer a = null;
//赋值
//a=null 所以抛出 NullPointerException
Optional<Integer> optional=Optional.of(a);
// 不会抛出异常
Optional<Integer> optional = Optional.ofNullable(a);
//判空
//isNotNull=false
boolean isNotNull = optional.isPresent();
//取值
//a=null 所以抛出NoSuchElementException 否则value=a
Integer value=optional.get();