Sam
Sam

Reputation: 6890

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

Upvotes: 54

Views: 57578

Answers (6)

Evgeny Kharitonov
Evgeny Kharitonov

Reputation: 1107

There is one more nice way to achieve this:

return Objects.requireNonNull(map_instance.get(key), "Specified key doesn't exist in map");

Pros:

  • pure Java - no libs
  • no redundant Optional - less garbage

Cons:

  • only NullPointerException - sometimes NoSuchElementException or custom exceptions are more desirable

Java 8 required

Upvotes: 36

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

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!

Upvotes: 7

Sir Montes
Sir Montes

Reputation: 952

I use Optional Java util class, e.g.

Optional.ofNullable(elementMap.get("not valid key"))
            .orElseThrow(() -> new ElementNotFoundException("Element not found"));

Upvotes: 66

Marcin Majkowski
Marcin Majkowski

Reputation: 420

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

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

Upvotes: 18

mort
mort

Reputation: 13588

Such a method does not exist for a Map in Java. You could create it by extending the Map class of course or by creating a wrapper class that contains the map and a tryGet method.

C# however does have a such a method: 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); 
   }

Upvotes: 2

Tomer
Tomer

Reputation: 17930

the way you are doing it is the way to go.

as a side note, your code doesn't make much sense since you will always return true, maybe you meant:

return map_instance.get(key);

Upvotes: 0

Related Questions