What is the best implementation for this general-purpose library method?
public static <K, V> boolean containsEntry(
Map<K, V> map, K key, V value) {}
Criteria for judging this puzzle, as with most coding puzzles, are in this order:
- Completeness
- Correctness
- Performance
- Beauty
- Receipt of PayPal contribution
EDIT:
Well, since it got closed, I might as well post the answer. I think this is probably optimal:
V valueForKey = map.get(key);
return (valueForKey == null)
? value == null && map.containsKey(key)
: valueForKey.equals(value);
A clever simple solution would be:
return map.entrySet().contains(
new AbstractMap.SimpleImmutableEntry<K, V>(key, value));
It does cause a trifle of heap pollution, though, so the first answer is probably better.