Search code examples
javadictionaryhashmap

Key existence checking utility in Map


I'm using the following code for checking if a key exists in a Map instance:

if (!map_instance.containsKey(key))
    throw new RuntimeException("Specified key doesn't exist in map");
else
   return map_instance.get(key);

My question is:

Is there a utility or Map implementation to simplify the above code, such as:

custom_map.get(key,"Specified key doesn't exist in map");

My goal is: if key does not exist in map, the map implementation throws an exception with the passed string.

I don't know whether or not my desire is reasonable?

(Sorry if I am using the wrong terminology or grammar, I am still learning the English language.)


Solution

  • You could take a look into the configuration map from Apache commons. It doesn't implements Map, but has a similar interface with a few Helper methods, like getString, getStringArray, getShort and so on.

    With this implementation you could use the method setThrowExceptionOnMissing(boolean throwExceptionOnMissing) and could catch it and handle as you want.

    Isn't exactly with a configurable message but from my point of view it doesn't make sense to throw a fixed exception just with a custom message since the exception type itself depends on the context where the get method is invoked. For example, if you perform a get of an user the exception would be something related to that, maybe UserNotFoundException, and not just a RuntimeException with the message: User not Found in Map!