Java8 - Optional

2019-07-04 00:00:00 Java8

本文参照于文章 Java8 Optional 简书 。

Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。该类的其他方法都是依赖于是否包含值,如orElse(),ifPresent()。可以保存类型T的值,或者仅仅保存null,不用显式的进行空值检查。Optional 类的引入很好的解决空指针异常。

java.util.Optional<T>
public final class Optional<T>
extends Object

T get()方法:

If a value is present in thisOptional, returns the value, otherwise throws NoSuchElementException.

void ifPresent(Consumer<? superT> consumer)

If a value is present, invoke the specified consumer with the value, otherwise do nothing.

booleanisPresent()

Return true if there is a value present, otherwise false.

<U> Optional<U>map(Function<? superT,? extends U> mapper)

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.

static <T> Optional<T>of(T value)

Returns an Optional with the specified present non-null value. Throw NullPointerException if the value is null.

static <T> Optional<T>ofNullable(T value)

Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

TorElse(T other)

Return the value if present, otherwise return other.

TorElseGet(Supplier<? extendsT> other)

Return the value if present, otherwise invoke other and return the result of that invocation.

public Optional<T> filter(Predicate<? super T> predicate)

If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an emptyOptional.

    原文作者:天长水远
    原文地址: https://zhuanlan.zhihu.com/p/37011689
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章