通过源码可以发现Optional是一个没有子类的工具类,它的作用主要就是为了解决避免NPE(NullPointException异常)。关于Optional的用法和详细分析,下面就来一步一步的进行分析;
public final class Optional {
private final T value;
private Optional() {
this.value = null;
}
public static Optional empty() {
@SuppressWarnings("unchecked")
Optional t = (Optional) EMPTY;
return t;
}
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
public static Optional of(T value) {
return new Optional<>(value);
}
public static Optional ofNullable(T value) {
return value == null ? empty() : of(value);
}
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
public boolean isPresent() {
return value != null;
}
public void ifPresent(Consumer super T> consumer) {
if (value != null)
consumer.accept(value);
}
public Optional filter(Predicate super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
public Optional map(Function super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
public Optional flatMap(Function super T, Optional> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
public T orElse(T other) {
return value != null ? value : other;
}
public T orElseGet(Supplier extends T> other) {
return value != null ? value : other.get();
}
public T orElseThrow(Supplier extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Optional)) {
return false;
}
Optional> other = (Optional>) obj;
return Objects.equals(value, other.value);
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
@Override
public String toString() {
return value != null
? String.format("Optional[%s]", value)
: "Optional.empty";
}
}
通过上面的Optional源码,可以发现Optional的构造器是私有的,那么构造一个Optional实例的方式就只有使用Optional提供的一些静态方法。那么我们最常用的方式有哪些呢?
/**
* Returns an empty {@code Optional} instance. No value is present for this
* Optional.
*
* @apiNote Though it may be tempting to do so, avoid testing if an object
* is empty by comparing with {@code ==} against instances returned by
* {@code Option.empty()}. There is no guarantee that it is a singleton.
* Instead, use {@link #isPresent()}.
*
* @param Type of the non-existent value
* @return an empty {@code Optional}
*/
public static Optional empty() {
@SuppressWarnings("unchecked")
Optional t = (Optional) EMPTY;
return t;
}
通过该方法,我们就可以发现该方法创建了一个空的Optional类,也就是构造的该Optional对象中的value属性的值为null。
/**
* Returns an {@code Optional} with the specified present non-null value.
*
* @param the class of the value
* @param value the value to be present, which must be non-null
* @return an {@code Optional} with the value present
* @throws NullPointerException if value is null
*/
public static Optional of(T value) {
return new Optional<>(value);
}
/**
* Constructs an instance with the value present.
*
* @param value the non-null value to be present
* @throws NullPointerException if value is null
*/
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
再粘贴处关于Objects中的requireNonNull方法:
public static T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
结合着两段代码,就可以非常清楚的看出来啦,该方法创建了一个非空的Optional对象,如果传入的T类型的obj为一个null的话,就会抛出一个NullPointerException异常。所以,使用该方法,就必须保证传入的值不能为空。
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static Optional ofNullable(T value) {
return value == null ? empty() : of(value);
}
关于这段代码,可能就更容易理解了吧!,该方法就是在空和非空中提取出来了一个既可以创建一个空或者非空的Optional方法,至于创建的Optional对象的value值是否为空,就取决于传入的value值是否为空,如果为空就构造一个空的Optional,如果不为空,就构造一个不为空的Optional对象。该方法,就经常用于对传入的数据不能判断是否为空的情况使用。
上面对如何实例化Optional对象的三种方法做出了一些了解。解析来,我们就来一步一步来看Optional方法给我们提供的其他方法:
/**
* If a value is present in this {@code Optional}, returns the value,
* otherwise throws {@code NoSuchElementException}.
*
* @return the non-null value held by this {@code Optional}
* @throws NoSuchElementException if there is no value present
*
* @see Optional#isPresent()
*/
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
通过get方法源代码应该不需要解释就能知道怎么用的了吧!该方法就是获取Optional对象中的value值,也就是我们创建Optional对象的时候给Optional传进去的的value值。注意:如果我们创建的是一个空的Optional对象的话,调用get方法的时候就会抛出空指针异常啦!
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
ifPresent方法通过源代码就很容易知道,就是判断value值是否为空,如果为空的话就会返回false,如果不为空的话,就返回true
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer super T> consumer) {
if (value != null)
consumer.accept(value);
}
isPresent方法接收一个Consumer类型的参数,该方法会在value不为空的时候调用consumer的accept方法。 所以,我们经常获取Optional对象中的value值,就是调用ifPresent方法来获取value值。
例子:
public class TestOptional {
public static void main(String[] args) {
Optional optional1 = Optional.of("hello world;");
Optional optional2 = Optional.empty();
optional1.ifPresent(System.out::println);//会打印hello world;
optional2.ifPresent(System.out::println);//不会打印任何信息
}
}
/**
* If a value is present, and the value matches the given predicate,
* return an {@code Optional} describing the value, otherwise return an
* empty {@code Optional}.
*
* @param predicate a predicate to apply to the value, if present
* @return an {@code Optional} describing the value of this {@code Optional}
* if a value is present and the value matches the given predicate,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the predicate is null
*/
public Optional filter(Predicate super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
该方法接收一个predicate类型的方法。该方法主要是获取能够满足value不为空并且满足predicate的test方法的Optional类型的对象。如果为空就换回一当前空的Optional对象,如果不满足Predicate接口中的test方法,就返回一个空的Optional对象。简单的来说:该方法就是为了过滤不为空并且满足用户自定义规则的Optional对象
例子:
public class TestOptional {
public static void main(String[] args) {
Optional optional1 = Optional.of("hello world;");
//如果value的长度大于5,就对value进行输出
optional1.filter(item->item.length()>5).ifPresent(System.out::println);
}
}
/**
* If a value is present, apply the provided mapping function to it,
* and if the result is non-null, return an {@code Optional} describing the
* result. Otherwise return an empty {@code Optional}.
*
* @apiNote This method supports post-processing on optional values, without
* the need to explicitly check for a return status. For example, the
* following code traverses a stream of file names, selects one that has
* not yet been processed, and then opens that file, returning an
* {@code Optional}:
*
* {@code
* Optional fis =
* names.stream().filter(name -> !isProcessedYet(name))
* .findFirst()
* .map(name -> new FileInputStream(name));
* }
*
* Here, {@code findFirst} returns an {@code Optional}, and then
* {@code map} returns an {@code Optional} for the desired
* file if one exists.
*
* @param The type of the result of the mapping function
* @param mapper a mapping function to apply to the value, if present
* @return an {@code Optional} describing the result of applying a mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null
*/
public Optional map(Function super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
该方法完全可以见名知意,就是对Optional对象中的value值进行一些操作,转换为另一种类型结果,并返回一个新的Optional对象进行封装。但是,如果调用map方法的Optional对象的value值为空的话,就会直接返回一个空的Optional对象。不为空就返回一个新的Optional对象,对象中的value值封装着另一个value的一些操作后的结果
例子:把一个字符串转换为整形类型的数据,并对转换后的数据乘以2,再输出到控制台
public class TestOptional {
public static void main(String[] args) {
Optional optional1 = Optional.of("1");
optional1.map(Integer::parseInt).map(item->2*item).ifPresent(System.out::println);
}
}
/**
* If a value is present, apply the provided {@code Optional}-bearing
* mapping function to it, return that result, otherwise return an empty
* {@code Optional}. This method is similar to {@link #map(Function)},
* but the provided mapper is one whose result is already an {@code Optional},
* and if invoked, {@code flatMap} does not wrap it with an additional
* {@code Optional}.
*
* @param The type parameter to the {@code Optional} returned by
* @param mapper a mapping function to apply to the value, if present
* the mapping function
* @return the result of applying an {@code Optional}-bearing mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null or returns
* a null result
*/
public Optional flatMap(Function super T, Optional> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
flatMap
方法看起来和map
方法特别的相似。不同点就是flatMap
方法接收的参数Function类型的参数中输出结果类型为Optional类型。从方法体中就可以非常明确的清楚啦;flatMap方法,接收的Function参数,在Function调用apply方法后,必须是手动的封装为Optional类型作为返回值,而map自动的给我们包装成Optional类型的对象。
例子:对于上面的例子,用flatMap进行实现
public class TestOptional {
public static void main(String[] args) {
Optional optional1 = Optional.of("1");
optional1.flatMap(item->Optional.of(Integer.parseInt(item)*2)).ifPresent(System.out::println);
}
}
/**
* Return the value if present, otherwise return {@code other}.
*
* @param other the value to be returned if there is no value present, may
* be null
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
该方法就是获取Optional的value值,如果value值为null就获取一个传入的默认值other。
/**
* Return the value if present, otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier} whose result is returned if no value
* is present
* @return the value if present otherwise the result of {@code other.get()}
* @throws NullPointerException if value is not present and {@code other} is
* null
*/
public T orElseGet(Supplier extends T> other) {
return value != null ? value : other.get();
}
该方法和上面的方法一样,只不过该方法获取value值为空的时候,而是去调用Supplier的get方法来获取值。
/**
* Return the contained value, if present, otherwise throw an exception
* to be created by the provided supplier.
*
* @apiNote A method reference to the exception constructor with an empty
* argument list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*
* @param Type of the exception to be thrown
* @param exceptionSupplier The supplier which will return the exception to
* be thrown
* @return the present value
* @throws X if there is no value present
* @throws NullPointerException if no value is present and
* {@code exceptionSupplier} is null
*/
public T orElseThrow(Supplier extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
该方法和orElse几乎一样,只不过如果value值为null的时候,就抛出一个异常。该异常时自定义哒。