views:

540

answers:

2

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:

  1. Completeness
  2. Correctness
  3. Performance
  4. Beauty
  5. 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.

A: 

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);
}
harto
Whoops, fixed the post, thanks.We'd like to support all possible values of 'key' and 'value'.
Kevin Bourrillion
+2  A: 
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.

jjnguy
Laurence Gonsalves
To be honest, I dunno...I straight copied it from the deleted answer.
jjnguy
there was a deleted answer? and you copied it? I'm kinda confused. Anyway, this looks correct, but is not as performant as it could be.
Kevin Bourrillion
Yup, someone answered and then deleted the answer. It looked correct so I decided it should still be an entry.
jjnguy