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 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.
public static <K, V> boolean containsEntry(Map<K, V> map, K key, V value) {
returns map.containsKey(key) & isEquals(map.get(key), value);
}
private static boolean isEqual(Object a, Object b) {
return a == null ? a == b : a.equals(b);
}
You can also inline isEqual method.
Presumably it's meant to return a boolean
:
public static <K, V> boolean containsEntry(Map<K, V> map, K key, V value) {
return map.containsKey(key) && map.get(key).equals(value);
}
精彩评论