java.util.Optional

原文链接

1、Optional作用

  • 类位于:java.util.Optional
  • 臭名昭著的空指针异常是导致Java应用程序失败的最常见原因;以前为了解决空指针异常,Google公司著名的Guava项目引入了Optional类,Guava通过使用检查空值的方式来防止代码污染,它鼓励程序员写更干净的代码;受到Google Guava的启发Optional类已经成为Java 8类库的一部分
  • Optional实际上是个容器,它可以保存类型T的值,或者仅仅保存null,Optional提供很多有用的方法,这样我们就不用显式进行空值检测
  • JDK8在线源码英文文档:https://nowjava.com/readcode/jdk8
  • JDK8在线源码中文文档:https://www.matools.com/api/java8

2、常用API

构造相关

        // 空值实例
        Optional<Object> empty = Optional.empty();
        // 非空值实例
        Optional<String> nonEmpty = Optional.of("123");
        // 可空值实例
        Optional<Object> maybeEmpty = Optional.ofNullable(null);

get / orElse / orElseGet / orElseThrow

        Optional<Object> empty = Optional.empty();

        // get方法遇到空值会抛出异常NoSuchElementException
        Object o = empty.get();

        // 如果存在,则返回值,否则返回传入的默认值
        Object orElse = empty.orElse("123");
        System.out.println(orElse);//123

        // 如果存在,则返回该值,否则返回 Supplier.get()的返回值
        Object orElseGet = empty.orElseGet(new Supplier<Object>() {
            @Override
            public Object get() {
                return "abc";
            }
        });
        System.out.println(orElseGet);//abc

        try {
            // 如果存在,返回该值,否则抛出异常(此异常是Supplier.get()返回的)
            Object o = empty.orElseThrow(new Supplier<Throwable>() {
                @Override
                public Throwable get() {
                    return new NullPointerException();
                }
            });
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

isPresent / ifPresent

        // 判断值是否存在
        System.out.println(empty.isPresent());// false

        // 有值才会执行accept方法
        empty.ifPresent(new Consumer<Object>() {
            @Override
            public void accept(Object o) {
                //
                System.out.println(o.hashCode());
            }
        });

filter

        Optional<String> s = Optional.of("11");
        // 如果存在值,并且该值与Predicate.test()匹配,则返回描述该值的Optional,否则返回空值的Optional
        Optional<String> s1 = s.filter(new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return false;
            }
        });
        System.out.println(s1);// Optional.empty

map / flatMap

  • map:apply返回的是Optional包装的值
  • flatMap:apply方法返回是Optional

        // map处理
        Optional<Object> optiona4 = Optional.ofNullable("abc");
        Optional<Object> o4 = optiona4.map(new Function<Object, Object>() {
            @Override
            public Object apply(Object o) {
                System.out.println(o);//abc
                return "123";
            }
        });
        System.out.println(o4.get());//123

        // flatMap处理
        Optional<Object> optiona5 = Optional.ofNullable("efg");
        Optional<String> optiona6 = optiona5.flatMap(new Function<Object, Optional<String>>() {
            @Override
            public Optional<String> apply(Object o) {
                System.out.println(o);//efg
                return Optional.of("456");
            }
        });
        System.out.println(optiona6.get());//456

3、源码翻译

package java.util;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * A container object which may or may not contain a non-null value.
 * 一个可能包含也可能不包含非null值的容器对象
 * If a value is present, {@code isPresent()} will return {@code true} and
 * {@code get()} will return the value.
 * 如果存在值,isPresent()将返回 true,get()将返回该值。
 *
 * <p>Additional methods that depend on the presence or absence of a contained
 * value are provided, such as {@link #orElse(Object) orElse()}
 * (return a default value if value not present) and
 * {@link #ifPresent(Consumer) ifPresent()} (execute a block
 * of code if the value is present).
 * 还提供了依赖于包含值是否存在的其他方法,例如 orElse(Object) orElse()(如果值不存在,则返回默认值)
 * 和 ifPresent(Consumer) ifPresent()(如果值存在,则执行代码块)。
 *
 * <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
 * class; use of identity-sensitive operations (including reference equality
 * ({@code ==}), identity hash code, or synchronization) on instances of
 * {@code Optional} may have unpredictable results and should be avoided.
 *
 * 这是一个 value-based 的类;
 * 在Optional实例上的身份敏感操作(包括引用相等性==、标识哈希代码或同步)可能会产生不可预知的结果,应避免使用。
 *
 * @since 1.8
 */
public final class Optional<T> {
    /**
     * Common instance for {@code empty()}.
     * empty()的常见实例
     */
    private static final Optional<?> EMPTY = new Optional<>();

    /**
     * If non-null, the value; if null, indicates no value is present
     * 如果非空,则为值;如果为 null,则表示不存在任何值
     */
    private final T value;

    /**
     * Constructs an empty instance.
     * 构造一个空实例
     *
     * @implNote Generally only one empty instance, {@link Optional#EMPTY},
     * should exist per VM.
     * 通常,每个 VM 只能存在一个空实例
     */
    private Optional() {
        this.value = null;
    }

    /**
     * Returns an empty {@code Optional} instance.  No value is present for this
     * Optional.
     * 返回一个空的Optional实例。此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()}.
     * todo 此处解释不是太明白,比较对象为空? 确保单例?
     * 尽管这样做可能很诱人,但请避免通过 == 与 Option.empty() 返回的实例来比较测试对象是否为空。
     * 不能保证它是单例。相反,请使用 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;
    }

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

    /**
     * Returns an {@code Optional} with the specified present non-null value.
     *
     * 返回具有指定的非空值的 Optional实例
     *
     * @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);
    }

    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     * 返回描述指定值的 Optional实例,如果非 null,则返回空的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);
    }

    /**
     * If a value is present in this {@code Optional}, returns the value,
     * otherwise throws {@code NoSuchElementException}.
     * 如果Optional里面有值,则返回该值,否则抛出异常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;
    }

    /**
     * Return {@code true} if there is a value present, otherwise {@code false}.
     * 如果存在值,则返回 true,否则返回 false
     *
     * @return {@code true} if there is a value present, otherwise {@code false}
     */
    public boolean isPresent() {
        return value != null;
    }

    /**
     * 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 如果值存在且consumer为空 就会抛出异常
     */
    public void ifPresent(Consumer<? super T> consumer) {
        if (value != null)
            consumer.accept(value);
    }

    /**
     * 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}.
     * 如果存在值,并且该值与Predicate.test()匹配,则返回描述该值的Optional,否则返回空值的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();
    }

    /**
     * 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}.
     * 如果存在值,则对其应用提供的映射函数,如果结果为非 null,则返回描述结果的 {@code Optional}。
     * 否则不存在值,返回空值的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>}:
     * 此方法支持对可选值进行后处理,而无需显式检查返回状态。
     * 例如,以下代码遍历文件名流,选择尚未处理的文件名流,然后打开该文件,返回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.
     * 在这里,findFirst返回一个Optional<String>,然后map返回所需文件的Optional<FileInputStream>(如果存在)。
     *
     * @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));
        }
    }

    /**
     * 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}.
     *
     * 如果存在值,请对其应用提供的 {@code 可选} 轴承映射函数,返回该结果,否则返回空的 {@code 可选}。
     *
     * 此方法类似于map,但提供的映射器的结果已经是 Optional,如果调用flatMap会用额外的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));
        }
    }

    /**
     * Return the value if present, otherwise return {@code other}.
     * 如果存在,则返回值,否则返回入参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;
    }

    /**
     * Return the value if present, otherwise invoke {@code other} and return
     * the result of that invocation.
     * 如果存在,则返回该值,否则返回 Supplier.get()的返回值
     *
     * @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();
    }

    /**
     * Return the contained value, if present, otherwise throw an exception
     * to be created by the provided supplier.
     * 如果存在,返回该值,否则抛出异常(此异常是Supplier.get()返回的)
     *
     * @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();
        }
    }

    /**
     * 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;
     * 它也是一个Optional
     * <li>both instances have no value present or;
     * 两个实例都不存在值或
     * <li>the present values are "equal to" each other via {@code equals()}.
     * 当前值通过 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}
     *
     * <ul> @param obj  @return {code true} 如果另一个对象“等于”这个对象,否则 {@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);
    }

    /**
     * Returns the hash code value of the present value, if any, or 0 (zero) if
     * no value is present.
     * 返回当前值的哈希代码值(如果有)或 0(零)(如果不存在任何值)
     *
     * @return hash code value of the present value or 0 if no value is present
     */
    @Override
    public int hashCode() {
        return Objects.hashCode(value);
    }

    /**
     * Returns a non-empty string representation of this Optional suitable for
     * debugging. The exact presentation format is unspecified and may vary
     * between implementations and versions.
     * 返回此 Optional 适合调试的非空字符串表示形式。
     * 确切的演示格式未指定,可能因实现和版本而异。
     *
     * @implSpec If a value is present the result must include its string
     * representation in the result. Empty and present Optionals must be
     * unambiguously differentiable.
     * 如果存在值,则结果必须在结果中包含其字符串表示形式。空和存在值的Optionals 必须明确可区分。
     *
     * @return the string representation of this instance
     */
    @Override
    public String toString() {
        return value != null
            ? String.format("Optional[%s]", value)
            : "Optional.empty";
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码充电宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值