目录
前记
Java8中引入了Optional新特性,用于更优雅的解决空指针异常,此次引用Java 8实战里面的描述:
在你的代码中始终如一地使用Optional,能非常清晰地界定出变量值的缺失是结构上的问
题,还是你算法上的缺陷,抑或是你数据中的问题。另外,我们还想特别强调,引入Optional
类的意图并非要消除每一个null引用。与此相反,它的目标是帮助你更好地设计出普适的API,
让程序员看到方法签名,就能了解它是否接受一个Optional的值。这种强制会让你更积极地将
变量从Optional中解包出来,直面缺失的变量值
Optional类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
Optional类是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值监测。
Optional类的引用很好的解决空指针异常。
方法
Optinal类是一个典型的单例模式的例子,其构造方法是私有的
通过一个私有字段生成Optional类实例
通过公共方法来访问该实例对象
特殊的地方是Optional类有一个公共的方法of()可以生成新的Optional类实例,详见下方of()方法
方法解析
1.empty()方法
它与of()方法相似,是一个静态方法,也用于创建Oprional对象,但是它没有参数,创建的是一个空的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 <T> Type of the non-existent value
* @return an empty {@code Optional}
*/
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
2.of()
of()方法是一个静态方法,用于创作Optional对象,它的参数必须是一个明确非null 的值。
示例
@Test
public void test() {
Optional<String> optional = Optional.of("Hello World");
if (optional.isPresent()) {
System.out.println(optional.get());
}
optional.ifPresent(System.out::println);
ConfigurationCustomizer configurationCustomizer = System.out::println;
System.out.println();
}
of()方法源码
/**
* Returns an {@code Optional} with the specified present non-null value.
*
* @param <T> 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 <T> Optional<T> of(T value) {
return new Optional<>(value);
}
3.ofNullable()方法
参数为null则调用empty()方法,否则调用of()方法
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> 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 <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
4.get()方法
从Optional实例中取value属性值,属性为null则抛出NoSuchElementException异常
/**
* 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;
}
5.isPresent()方法
判断Optional对象是否为空。
返回的是一个boolean值,非空返回true。
/**
* 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;
}
6.ifPresent()方法
参数是一个Consumer函数式接口,不是null执行Consumer.accept。
/**
* 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);
}
7.filter()方法
filter()方法的参数是一个Predicate函数式接口,源码如下
/**
* 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<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
8.map()方法
map()方法的参数是一个Function函数式接口,源码如下
/**
* 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<FileInputStream>}:
*
* <pre>{@code
* Optional<FileInputStream> fis =
* names.stream().filter(name -> !isProcessedYet(name))
* .findFirst()
* .map(name -> new FileInputStream(name));
* }</pre>
*
* Here, {@code findFirst} returns an {@code Optional<String>}, and then
* {@code map} returns an {@code Optional<FileInputStream>} for the desired
* file if one exists.
*
* @param <U> 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<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
9.flatMap()方法
与map()方法相似,参数也是一个Function函数式接口,源码如下:
/**
* 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 <U> 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<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
注意:使用flatMap()方法可避免将一个Optional包装在另一个Optional中。如果某对象实例的属性本身就为Optional包装过的类型,那么就要使用flatMap方法,例如Optional<T>类型的,所以不用再使用Optional进行包装,这时就要选用flatMap方法,对于返回值是其他类型,需要Optional进行包装,如String类型,就需要使用map方法在其外面包装一层Optional对象
10.orElse()方法
与get()方法类似用于获取Optional对象中的value。如果value为null则将orElse()方法的参数)返回否则返回value值。
/**
* 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;
}
11.orElseGet()方法
用于获取Optional对象中的value。如果value为null则将orElseGet()方法的参数(是一个Supplier接口)中调用的返回值当返回,否则返回value值。
/**
* 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();
}
12.orElseThrow()方法
用于获取Optional对象中的value。如果value不为null,返回value值,否则抛出Supplier.get()(orElseThrow()方法的参数是一个Supplier接口)
实际上相当于value为null时,返回Supplier参数(函数式参数)的返回值,详见下三个例子:
public static void main(String[] args) {
Person son = null;
//先判断son是否为null,如果为不为null则返回当前对象,如果为null则返回新创建的对象
BrandDTO optional = Optional.ofNullable(son).orElseGet(() -> new Person());
}
import java.util.function.Supplier;
/**
* 使用supplier函数式接口求数组的最大值
*/
public class ArrMaxValue {
public static int getMaxValue(Supplier<Integer> sup){
return sup.get();
}
public static void main(String[] args) {
// 创建数组
int[] arr = {100,20,50,30,99,101,-50};
int maxValue = getMaxValue(()->{
int max = arr[0];
for (int i : arr) {
if(i > max){
max = i;
}
}
return max;
});
System.out.println("数组中的最大值为:" + maxValue);
}
}
//无需提供输入参数,返回一个T类型的执行结果
Supplier<String> supplier = () -> "Hello Jack!";
System.out.println(supplier.get()); // Hello Jack!
orElseThrow()方法源码:
/**
* 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 <X> 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 <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
equals()方法
重写于Object类,用于把传入的参数(参数为一个类实例)与Optional对比,如果传入的实例是上文中已创建的Optional实例或者其是Optional类型且value和上文的Optional实例相同,则返回true,否则返回false。
源码如下:
/**
* Indicates whether some other object is "equal to" this Optional. The
* other object is considered equal if:
* <ul>
* <li>it is also an {@code Optional} and;
* <li>both instances have no value present or;
* <li>the present values are "equal to" each other via {@code equals()}.
* </ul>
*
* @param obj an object to be tested for equality
* @return {code true} if the other object is "equal to" this object
* otherwise {@code false}
*/
@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);
}