泛型类
构造方法私有
private final T value;
private static final Optional<?> EMPTY = new Optional<>();
通过两个静态方法来获取实例。
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
of : 如果 value 为空,则抛异常
ofNullable : 如果value为空,则返回 带有空值的 实例
java.util.function.Consumer#accept
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
java.util.function.Predicate#test
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
这个filter 跟 Stream的filter不一样。这个filter 返回的是 Optional对象实例。
java.util.function.Function#apply
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));
}
}
返回值
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
public T orElse(T other) {
return value != null ? value : other;
}
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();
}
}