Skip to content

Instantly share code, notes, and snippets.

@nithinivi
Created August 9, 2024 04:11
Show Gist options
  • Save nithinivi/bf6b47741b23816d47fe8c91b7bcaa36 to your computer and use it in GitHub Desktop.
Save nithinivi/bf6b47741b23816d47fe8c91b7bcaa36 to your computer and use it in GitHub Desktop.
PredicateExhaustiveSelector
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Objects;
import java.util.function.Predicate;
public class PredicateExhaustiveSelector<O, V> extends HashMap<Predicate<O>, V> {
/**
* Returns the value to which the specified object is true for the mapped predicate,
* or {@code null} if this map contains no mapping for the key. if multiple predicates are
* true throws NonExhaustiveSelectionException exception
* .
* @param object which used to evaluate the predicates
* @return Returns the value to which the specified object is true for the mapped predicate
* @throws NonExhaustiveSelectionException
*/
@Override
@SuppressWarnings("unchecked")
public V get(@NotNull Object object) {
V value = null;
for (var entry : entrySet()) {
if (!entry.getKey().test((O) object)) {
continue;
}
if (Objects.isNull(value)) {
value = entry.getValue();
} else {
throw new NonExhaustiveSelectionException();
}
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment