public class StreamableOptional<T> extends Object
Optional that provides the very missed stream() method useful for
flatMapping a Stream of Optional (i.e. only keep present values).
example: the good
collection.stream().flatMap(item -> StreamableOptional.ofNullable(item.getNullableProperty()).stream())
would replace the bad:
collection.stream().map(item -> Optional.ofNullable(item.getNullableProperty())).filter(Optional::isPresent).map(Optional::get)
or the ugly:
collection.stream().flatMap(item -> Optional.ofNullable(item.getNullableProperty()).map(Stream::of).orElseGet(Stream::empty))
| Modifier and Type | Method and Description |
|---|---|
static <T> StreamableOptional<T> |
empty() |
boolean |
equals(Object o) |
StreamableOptional<T> |
filter(Predicate<? super T> predicate) |
<U> StreamableOptional<U> |
flatMap(Function<? super T,StreamableOptional<U>> mapper) |
int |
hashCode() |
void |
ifPresent(Consumer<? super T> consumer) |
<U> StreamableOptional<U> |
map(Function<? super T,? extends U> mapper) |
static <T> StreamableOptional<T> |
of(T value) |
static <T> StreamableOptional<T> |
ofNullable(T value) |
static <T> StreamableOptional<T> |
ofOptional(Optional<T> optional)
Builds a StreamableOptional around the given
Optional |
T |
orElse(T other) |
T |
orElseGet(Supplier<? extends T> other) |
<X extends Throwable> |
orElseThrow(Supplier<? extends X> exceptionSupplier) |
Stream<T> |
stream()
Turns this optional into a
Stream |
Optional<T> |
toOptional() |
public void ifPresent(Consumer<? super T> consumer)
consumer - consumerOptional.ifPresent(java.util.function.Consumer)public StreamableOptional<T> filter(Predicate<? super T> predicate)
predicate - predicateOptional.filter(java.util.function.Predicate)public <U> StreamableOptional<U> map(Function<? super T,? extends U> mapper)
U - umapper - mapperOptional.map(java.util.function.Function)public <U> StreamableOptional<U> flatMap(Function<? super T,StreamableOptional<U>> mapper)
U - umapper - mapperOptional.flatMap(java.util.function.Function)public T orElse(T other)
other - otherOptional.orElse(Object)public T orElseGet(Supplier<? extends T> other)
other - otherOptional.orElseGet(java.util.function.Supplier)public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
X - xexceptionSupplier - exceptionSupplierX - xX extends ThrowableOptional.orElseThrow(java.util.function.Supplier)public Stream<T> stream()
StreamStream of the one value contained within this optional if it is present, an empty stream elsepublic static <T> StreamableOptional<T> of(T value)
T - tvalue - valueOptional.of(Object)public static <T> StreamableOptional<T> ofNullable(T value)
T - tvalue - valueOptional.ofNullable(Object)public static <T> StreamableOptional<T> ofOptional(Optional<T> optional)
OptionalT - toptional - a regular Optionalpublic static <T> StreamableOptional<T> empty()
T - tOptional.empty()Copyright © 2014–2015. All rights reserved.