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:
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 allocate an instance, but it gives the map implementation a little more opportunity to do something optimal.
public static <K, V> boolean containsEntry(Map<K, V> map, K key, V value) {
returns map.containsKey(key) && isEqual(map.get(key), value);
}
private static boolean isEqual(Object a, Object b) {
return a == null ? a == b : a.equals(b);
}
Copied from deleted post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With