Java HashMap getOrDefault() Method

Java HashMap Java HashMap

The getOrDefault() method gets the value corresponding to the specified key. If the key is not found, it returns the set default value.

The syntax of the getOrDefault() method is:

hashmap.getOrDefault(Object key, V defaultValue)

Note:hashmap is an object of the HashMap class.

Parameter description:

  • key - The key
  • defaultValue - The default value returned when the specified key does not exist in the mapping relationship.

Return Value

Returns the value mapped to the key. If the given key is not found in the mapping, returns the specified default value.

Example

The following example demonstrates the use of the getOrDefault() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // The mapping for key exists in the HashMap
        // Not Found - If the HashMap does not have this key, return the default value
        String value1 = sites.getOrDefault(1, "Not Found");
        System.out.println("Value for key 1:  " + value1);

        // The mapping for key does not exist in the HashMap
        // Not Found - If the HashMap does not have this key, return the default value
        String value2 = sites.getOrDefault(4, "Not Found");
        System.out.println("Value for key 4: " + value2);
    }
}

Executing the above program outputs the result:

Value for key 1:  Google
Value for key 4: Not Found

Note:We can use theHashMap containsKey() methodto check whether the HashMap has a specific key.

Java HashMap Java HashMap

Other Extensions