Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java Map puzzle [closed]

Tags:

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 allocate an instance, but it gives the map implementation a little more opportunity to do something optimal.

like image 294
Kevin Bourrillion Avatar asked Nov 06 '09 05:11

Kevin Bourrillion


1 Answers

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.

like image 67
4 revs, 2 users 90% Avatar answered Oct 13 '22 01:10

4 revs, 2 users 90%