Key existence checking utility in Map

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


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"); });