欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDK1.8新特性之Optional类(一)

程序员文章站 2022-02-06 11:31:42
...
  • 认识Optional

类注解源码:


/**
 * A container object which may or may not contain a non-null value.
 * If a value is present, {@code isPresent()} will return {@code true} and
 * {@code get()} will return the value.
 *
 * <p>Additional methods that depend on the presence or absence of a contained
 * value are provided, such as {@link #orElse(java.lang.Object) orElse()}
 * (return a default value if value not present) and
 * {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block
 * of code if the value is present).
 *
 * <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.
 *
 * @since 1.8
 */
public final class Optional<T> {

    /**
     * Common instance for {@code empty()}.
     */
    private static final Optional<?> EMPTY = new Optional<>();

    /**
     * If non-null, the value; if null, indicates no value is present
     */
    private final T value;
   
}

从类注解中我们可以看出,Optional是一个可以容纳空对象的object容器,可通过isPresent()方法来判断值是否存在,通过get()方法获取值。附加方法的使用取决于容器中的值是否存在。看来,Optional类的主要特性是区分对象是否为空,并分别作出处理的容器类。下面,我们看看这个容器在代码中是怎么使用的。

  • API讲解

1.empty() 获取一个空容器。返回一个指向new 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(T value)  获取一个容纳非空对象的容器。

/**
     * 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(T value) 获取一个可容纳空对象的容器。

/**
     * 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() 获取容器容纳的对象,当对象为空时抛出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;
    }

通过代码实践一下:

package optional;

import java.util.Optional;

public class User {

	private String name, id;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "User{" +
				"name='" + name + '\'' +
				", id='" + id + '\'' +
				'}';
	}

	public static void main(String[] args) {
		User user = new User();
		User nullUser = null;
		Optional<User> userOpt = Optional.ofNullable(user);
		Optional<User> nullUserOpt = Optional.ofNullable(nullUser);
		System.out.println(userOpt.get());
		System.out.println(nullUserOpt.get());
	}
}

 控制台输出内容:

User{name='null', id='null'}
Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.util.Optional.get(Optional.java:135)
	at optional.User.main(User.java:39)

5.isPresent() 判断容纳的对象是否为空。

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

代码实践:

        System.out.println(userOpt.isPresent());
	System.out.println(nullUserOpt.isPresent());

控制台输出:
        true
        false

6.ifPresent(Consumer<? super T> consumer)当容纳的对象存在时,执行参数中的方法。

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

代码实践:

        userOpt.ifPresent(item -> System.out.println(item));
	nullUserOpt.ifPresent(item -> System.out.println(item));
控制台:
        User{name='null', id='null'}

7.filter(Predicate<? super T> predicate)通过一定条件过滤容器,返回null,this,或者空容器。

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

代码实践:

	Optional<User> optional = nullUserOpt.filter((User item) -> item == null);
	System.out.println(optional.isPresent());
	Optional<User> opt1 = userOpt.filter((User item) -> item == null);
	System.out.println(opt1.isPresent());
	Optional<User> opt2 = userOpt.filter((User item) -> item != null);
	System.out.println(opt2.get());
控制台输出:
        false
        false
        User{name='null', id='null'}

8.map(Function<? super T, ? extends U> mapper)获取容纳参数方法的返回值的容器。

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

代码实践:

		user.setId("123");
		Optional<String> idOpt = userOpt.map(User::getId);
		System.out.println(idOpt.get());
控制台:
    123

 9.flatMap(Function<? super T, Optional<U>> mapper)目的同上,不同的是参数方法的返回值必须由Optional包装。

代码实践:

user.setId("123");
Optional<String> idOpt = userOpt.flatMap(item -> Optional.ofNullable(item.getId()));
System.out.println(idOpt.get());

控制台:123

10.orElse(T other) 当容纳的对象为空时,返回参数中的对象。

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

代码实践:

	User user1 = nullUserOpt.orElse(user);
	System.out.println(user1);
控制台:
        User{name='null', id='null'}

11.orElseGet(Supplier<? extends T> 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();
    }

代码实践(本次直接使用userOpt):

	User user1 = nullUserOpt.orElseGet(userOpt::get);
	System.out.println(user1);
控制台输出:
        User{name='null', id='null'}

12.orElseThrow(Supplier<? extends X> exceptionSupplier) throws X 当容器中对象为空时,抛出参数中的异常。

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

代码实践:

		try {
			nullUserOpt.orElseThrow(Exception::new);
		}catch (Exception e){
			System.err.println(e);
		}
控制台输出:
java.lang.Exception

13.equals(Object obj)对比容器中的对象

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

代码实践:

		boolean equals = userOpt.equals(Optional.ofNullable(user));
		System.out.println(equals);
控制台输出:
true

14.hashCode() 获取容器中对象的哈希值

/**
     * Returns the hash code value of the present value, if any, or 0 (zero) if
     * no value is present.
     *
     * @return hash code value of the present value or 0 if no value is present
     */
    @Override
    public int hashCode() {
        return Objects.hashCode(value);
    }

 

相关标签: Optional jdk1.8