All Downloads are FREE. Search and download functionalities are using the official Maven repository.

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 mapper) {
		if (empty) {
			return empty();
		}
		return of(mapper.apply(content));
	}

	public  OptionalValue flatMap(Function> mapper) {
		if (empty) {
			return empty();
		}
		return mapper.apply(content);
	}

	public T orElse(T other) {
		return empty
			? other
			: content;
	}

	public T orElseGet(Supplier other) {
		return empty
			? other.get()
			: content;
	}

	public  T orElseThrow(Supplier exceptionSupplier) throws X {
		if (empty) {
			throw exceptionSupplier.get();
		}
		return content;
	}

	public void ifPresent(Consumer consumer) {
		if (!empty) {
			consumer.accept(content);
		}
	}

	public void ifPresentOrElse(Consumer consumer, Runnable emptyAction) {
		if (empty) {
			emptyAction.run();
		} else {
			consumer.accept(content);
		}
	}

	public Stream stream() {
		if (empty) {
			return Stream.empty();
		} else {
			return Stream.of(content);
		}
	}
}