How's about Collections.getSafe(...) for Map<?, ?>, which wouldn't return null?

assembling signals assembling.signals at
Sun Oct 25 19:42:30 UTC 2009


I am thinking about a new method getSafe(...) for the "Collections" utility class.

It would do get(...) on a map, but instead of returning null (when an entry is not found),
it would throw NoSuchElementException.

public static <K,V> V getSafe(Map<K,V> map, Object key){
  if(!map.containsKey(key)) {
    throw new NoSuchElementException(/* some message here */);

  return map.get(key);

What do you think about it?

More information about the core-libs-dev mailing list