
net.amygdalum.testrecorder.util.OptionalValue Maven / Gradle / Ivy
The newest version!
package net.amygdalum.testrecorder.util;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class OptionalValue {
private static final OptionalValue> EMPTY = new OptionalValue<>(true);
private boolean empty;
private T content;
private OptionalValue(boolean empty) {
this.content = null;
this.empty = empty;
}
public OptionalValue(T content) {
this.content = content;
}
public static OptionalValue of(Optional value) {
if (value == null) {
return of((T) null);
}
return value.isPresent()
? of(value.get())
: empty();
}
public static OptionalValue of(T value) {
return new OptionalValue<>(value);
}
@SuppressWarnings("unchecked")
public static OptionalValue empty() {
return (OptionalValue) EMPTY;
}
public OptionalValue filter(Predicate predicate) {
if (empty || !predicate.test(content)) {
return empty();
}
return this;
}
public OptionalValue map(Function super T, ? extends S> mapper) {
if (empty) {
return empty();
}
return of(mapper.apply(content));
}
public OptionalValue flatMap(Function super T, OptionalValue> mapper) {
if (empty) {
return empty();
}
return mapper.apply(content);
}
public T orElse(T other) {
return empty
? other
: content;
}
public T orElseGet(Supplier extends T> other) {
return empty
? other.get()
: content;
}
public T orElseThrow(Supplier extends X> exceptionSupplier) throws X {
if (empty) {
throw exceptionSupplier.get();
}
return content;
}
public void ifPresent(Consumer super T> consumer) {
if (!empty) {
consumer.accept(content);
}
}
public void ifPresentOrElse(Consumer super T> consumer, Runnable emptyAction) {
if (empty) {
emptyAction.run();
} else {
consumer.accept(content);
}
}
public Stream stream() {
if (empty) {
return Stream.empty();
} else {
return Stream.of(content);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy