Map Key Verification Utility

I use the following code to check for a key 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 implementation of Map to simplify the above code, for example:

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

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

I do not know if my desire is reasonable?

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

+8
java dictionary hashmap
source share
4 answers

You can see the configuration map from apache commons here . It does not implement Map , but has a similar interface with several Helper methods such as getString , getStringArray , getShort , etc.

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

Not exactly with a custom message, but from my point of view it does not make sense to throw a fixed exception only with a custom message, since the type of exception itself depends on the context in which the get method is called. For example, if you are receiving a user, the exception will be associated with what perhaps UserNotFoundException , not just RuntimeException with the message: User not found on map!

+3
source share

In Java 8, you can use computeIfAbsent from Map , for example:

 map.computeIfAbsent("invalid", key -> { throw new RuntimeException(key + " not found"); }); 
+6
source share

This method does not exist for Maps in Java. You can create it by extending the map class, or by creating a wrapper class containing the map and the tryGet method.

However, C # has a method like this: Directory.TryGetValue()

 public class MyMap { public Map<Object, Object> map = new HashMap<Object, Object>(); public Object tryGet(Object key, String msg) { if(!map.containsKey(key)) throw new IllegalArgumentException(msg); return map.get(key); } 
+1
source share

the way you do it is the way.

as a side note, your code does not make much sense, since you will always return true, maybe you meant:

 return map_instance.get(key); 
0
source share

All Articles