/** * Return the value if present, otherwise invoke {@code other} and return * the result of that invocation. */ 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. */ public <X extendsThrowable> T orElseThrow(Supplier<? extends X> exceptionSupplier)throws X { if (value != null) { return value; } else { throw exceptionSupplier.get(); } }
/** * If a value is present, invoke the specified consumer with the value, * otherwise do nothing. */ publicvoidifPresent(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}. * */ public Optional<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate); if (!isPresent()) returnthis; 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}. */ 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)); } } }