HashMap to return default value for non-found keys? HashMap to return default value for non-found keys? java java

HashMap to return default value for non-found keys?


In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found.


[Update]

As noted by other answers and commenters, as of Java 8 you can simply call Map#getOrDefault(...).

[Original]

There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap:

public class DefaultHashMap<K,V> extends HashMap<K,V> {  protected V defaultValue;  public DefaultHashMap(V defaultValue) {    this.defaultValue = defaultValue;  }  @Override  public V get(Object k) {    return containsKey(k) ? super.get(k) : defaultValue;  }}


Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g.,

Map<String, String> map = new DefaultedMap<>("[NO ENTRY FOUND]");String surname = map.get("Surname"); // surname == "[NO ENTRY FOUND]"

You can also pass in an existing map if you're not in charge of creating the map in the first place.