Java Utility Library

Java HashMap - getOrDefault() Method



The java.util.HashMap.getOrDefault() method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Syntax

public V getOrDefault(Object key, V defaultValue)

Here, V is the type of value maintained by the container.


Parameters

key Specify the key whose associated value is to be returned.
defaultValue Specify the default mapping of the key.

Return Value

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Exception

NA

Example:

In the example below, the java.util.HashMap.getOrDefault() method returns the value to which the specified key is mapped in the given HashMap.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash map
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating hash map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, null);
    MyMap.put(105, "Sam");

    //printing the value associated with
    //specified key of the HashMap
    System.out.println("key 101: " + MyMap.getOrDefault(101, "Blank"));
    System.out.println("key 102: " + MyMap.getOrDefault(102, "Blank"));
    System.out.println("key 104: " + MyMap.getOrDefault(104, "Blank"));
    System.out.println("key 107: " + MyMap.getOrDefault(107, "Blank"));
  }
}

The output of the above code will be:

key 101: John
key 102: Marry
key 104: null
key 107: Blank

❮ Java.util - HashMap