类结构
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));
}
}