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

com.g2forge.alexandria.java.function.optional.OptionalFunction Maven / Gradle / Ivy

There is a newer version: 0.0.18
Show newest version
package com.g2forge.alexandria.java.function.optional;

import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

import com.g2forge.alexandria.java.fluent.optional.function.IOptionalFunctional;

@FunctionalInterface
public interface OptionalFunction extends Function> {
	public static  OptionalFunction empty() {
		return i -> Optional.empty();
	}

	public static  OptionalFunction of(Map map) {
		return i -> map.containsKey(i) ? Optional.of(map.get(i)) : Optional.empty();
	}

	public static  OptionalFunction of(Object input, O output) {
		return of(input, () -> output);
	}

	public static  OptionalFunction of(Object input, Supplier output) {
		return i -> input.equals(i) ? Optional.of(output.get()) : Optional.empty();
	}

	/**
	 * Create a function which will fall back to the return values from fallback when this function doesn't return a value.
	 * 
	 * @param fallback The function to call back to when this returns no value.
	 * @return A function which will return values from this or, if needed, the fallback.
	 * @see IOptionalFunctional#fallback(Function)
	 */
	public default Function fallback(Function fallback) {
		return i -> {
			final Optional o = apply(i);
			return o.isPresent() ? o.get() : fallback.apply(i);
		};
	}

	/**
	 * Create a optional function where any value returned from override overrides the value this function would return.
	 * 
	 * @param override The function whose return values, when any, override our own.
	 * @return An optional function which returns the results of override if any, and the result of this optional function otherwise.
	 * @see IOptionalFunctional#override(IOptionalFunctional)
	 */
	public default OptionalFunction override(OptionalFunction override) {
		return i -> {
			final Optional o = override.apply(i);
			return o.isPresent() ? o : apply(i);
		};
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy