Easy Tutorial
❮ Number Todegrees Net Port ❯

Java HashMap getOrDefault() Method

The getOrDefault() method retrieves the value mapped to a specified key, or returns a default value if the key is not found.

The syntax for the getOrDefault() method is:

hashmap.getOrDefault(Object key, V defaultValue)

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

Returns the value corresponding to the key, or the specified default value if the key is not found in the map.

Example

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

import java.util.HashMap;

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

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

        // Key exists in the HashMap
        // Not Found - returns default value if the key is not in the HashMap
        String value1 = sites.getOrDefault(1, "Not Found");
        System.out.println("Value for key 1: " + value1);

        // Key does not exist in the HashMap
        // Not Found - returns default value if the key is not in the HashMap
        String value2 = sites.getOrDefault(4, "Not Found");
        System.out.println("Value for key 4: " + value2);
    }
}

Executing the above program outputs:

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

Note: We can use the containsKey() method to check if a specific key exists in the HashMap.

❮ Number Todegrees Net Port ❯