Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 853
Sam Avatar asked Jul 08 '12 13:07

Sam


People also ask

How do you check for the existence of a key in a map?

To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...

How can I tell if a map key is null?

containsKey() to determine if the Map entry has a key entry. If it does and the Map returns null on a get call for that same key, then it is likely that the key maps to a null value. In other words, that Map might return "true" for containsKey(Object) while at the same time returning " null " for get(Object) .

What happens if we put a key object in a HashMap which exists?

What happens if we put a key object in a HashMap which exists? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.


2 Answers

I use Optional Java util class, e.g.

Optional.ofNullable(elementMap.get("not valid key"))             .orElseThrow(() -> new ElementNotFoundException("Element not found")); 
like image 151
Sir Montes Avatar answered Oct 07 '22 18:10

Sir Montes


In Java 8 you can use computeIfAbsent from Map, like this:

map.computeIfAbsent("invalid", key -> { throw new RuntimeException(key + " not found"); }); 
like image 30
Marcin Majkowski Avatar answered Oct 07 '22 17:10

Marcin Majkowski