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.)
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 ...
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? Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the previous object.
I use Optional Java util class, e.g.
Optional.ofNullable(elementMap.get("not valid key")) .orElseThrow(() -> new ElementNotFoundException("Element not found"));
In Java 8 you can use computeIfAbsent
from Map
, like this:
map.computeIfAbsent("invalid", key -> { throw new RuntimeException(key + " not found"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With