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

Stephen Colebourne scolebourne at
Mon Oct 26 13:03:52 UTC 2009

This isn't one I've seen much use for.

It would also be possible to write it as a decorating wrapper for a
map, rather than as a static utility method.


2009/10/25 assembling signals <assembling.signals at>:
> Hello!
> 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.
> @Nonnull
> 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