Key existence checking utility in Map

31,204

Solution 1

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!

Solution 2

I use Optional Java util class, e.g.

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

Solution 3

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

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

Solution 4

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

Solution 5

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); 
   }
Share:
31,204
Sam
Author by

Sam

My act is: "I don't know particular things, but I am trying learning new things any day." I like always learning new things about software or maybe hardware, especially in programming languages.

Updated on June 14, 2020

Comments

  • Sam
    Sam about 4 years

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

  • user1329572
    user1329572 almost 12 years
    composition over inheritance, imo.
  • Marko Topolnik
    Marko Topolnik almost 12 years
    The unfortunate side of composition is the disgusting amount of boilerplate.
  • Sam
    Sam almost 12 years
    Thanks for your answer, can you show a sample?I don't familiar with Apache Common Configuration.
  • Sam
    Sam almost 12 years
    yes, my means is get method invoking, I edited my question.
  • Francisco Spaeth
    Francisco Spaeth almost 12 years
    MapConfiguration mc = new MapConfiguration(properties); mc.setThrowExceptionOnMissing(true); mc.getString("key"); if key doesn't exists a NoSuchElementExcpetion will be thrown
  • monarch_dodra
    monarch_dodra almost 6 years
    Don’t do this. "computeIfAbsent" is meant as a mutation operation. So if your map happens to be an UnmodifiableMap, or a Guava or Eclipse Collection ImmutableMap, or a ProtoMap, this call will immediately fail with some sort of UnsupportedOperationException. A Java8 equivalent could be: Optional.fromNullable(map.get("invalid")).orElseThrow(() -> new RuntimeException(key + " not found")); This has slightly more bloat, but has the advantage of correctness.
  • Herr Derb
    Herr Derb over 4 years
    I think that's the best solution. But better use NoSuchElementException
  • avalori
    avalori about 4 years
    Good proposal, but it doesn't work when the map has an entry with null as a key on the map.as it would throw the exception rather than returning the associated value.
  • avalori
    avalori about 4 years
    Great comment. But the proposed alternative doesn't work when there is an entry with null as a key on the map, as it would throw the exception rather than returning the associated value.
  • TodoCleverNameHere
    TodoCleverNameHere over 2 years
    This totally works, however, it's an abuse of the Optional data type per its author: stackoverflow.com/a/26328555 Optional is to be used as a return type, not as a way to branch through chaining in operational code.