Optional源码阅读

类结构

public final class Optional<T>

核心变量

 private static final Optional<?> EMPTY = new Optional<>();
 private final T value;
    public static<T> Optional<T> empty() {
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }

不能为空,为空会报错.

    public static <T> Optional<T> of(T value) {
        return new Optional<>(value);
    }
    //
    private Optional(T value) {
        this.value = Objects.requireNonNull(value);
    }

允许为空的

    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

太简单了.

    public T orElse(T other) {
        return value != null ? value : other;
    }

调用的时候再返回.
Return the value if present, otherwise invoke other and return the result of that invocation.

    public T orElseGet(Supplier<? extends T> other) {
        return value != null ? value : other.get();
    }

看看这个泛型是如何使用的.

    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
        if (value != null) {
            return value;
        } else {
            throw exceptionSupplier.get();
        }
    }

如果存在就接受一个consumer.

    public void ifPresent(Consumer<? super T> consumer) {
        if (value != null)
            consumer.accept(value);
    }

对value进行一次映射操作.

    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));
        }
    }

过滤一次操作.如果value满足测试调减,才返回value否则为空.

    public Optional<T> filter(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate);
        if (!isPresent())
            return this;
        else
            return predicate.test(value) ? this : empty();
    }

flapMap.类似map.但是flapmap不会再用Optional包装了.
map里的最后一行是Optional.ofNullable(mapper.apply(value)).
flapMap是mapper.apply(value).
This method is similar to map(Function), but the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional.

    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));
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容