Created
August 9, 2024 04:11
-
-
Save nithinivi/bf6b47741b23816d47fe8c91b7bcaa36 to your computer and use it in GitHub Desktop.
PredicateExhaustiveSelector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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