com.yahoo.collections.Optionals Maven / Gradle / Ivy
package com.yahoo.collections;
import com.google.common.collect.Comparators;
import java.util.Optional;
import java.util.function.BinaryOperator;
/**
* @author jonmv
*/
public class Optionals {
private Optionals() { }
/** Returns the first non-empty optional, or empty if all are empty. */
@SafeVarargs
public static Optional firstNonEmpty(Optional... optionals) {
for (Optional optional : optionals)
if (optional.isPresent())
return optional;
return Optional.empty();
}
/** Returns the non-empty optional with the lowest value, or empty if all are empty. */
@SafeVarargs
public static > Optional min(Optional... optionals) {
Optional best = Optional.empty();
for (Optional optional : optionals)
if (best.isEmpty() || optional.isPresent() && optional.get().compareTo(best.get()) < 0)
best = optional;
return best;
}
/** Returns the non-empty optional with the highest value, or empty if all are empty. */
@SafeVarargs
public static > Optional max(Optional... optionals) {
Optional best = Optional.empty();
for (Optional optional : optionals)
if (best.isEmpty() || optional.isPresent() && optional.get().compareTo(best.get()) > 0)
best = optional;
return best;
}
/** Returns whether either optional is empty, or both are present and equal. */
public static boolean equalIfBothPresent(Optional first, Optional second) {
return first.isEmpty() || second.isEmpty() || first.equals(second);
}
/** Returns whether the optional is empty, or present and equal to the given value. */
public static boolean emptyOrEqual(Optional optional, T value) {
return optional.isEmpty() || optional.equals(Optional.of(value));
}
}