Easy Tutorial
❮ Java String Replaceall Exception Chain ❯

Java HashMap putIfAbsent() Method

Java HashMap

The putIfAbsent() method checks if the specified key exists, and if it does not, it inserts the key/value pair into the HashMap.

The syntax for the putIfAbsent() method is:

hashmap.putIfAbsent(K key, V value)

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

If the specified key already exists in the HashMap, it returns the value associated with that key. If the specified key does not exist in the HashMap, it returns null.

Attention: If the specified key was previously associated with a null value, the method also returns null.

Example

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

Example

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 does not exist in the HashMap
        sites.putIfAbsent(4, "Weibo");

        // Key exists in the HashMap
        sites.putIfAbsent(2, "Wiki");
        System.out.println("Updated sites HashMap: " + sites);
    }
}

Executing the above program outputs:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Updated sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao, 4=Weibo}

In the example above, we created a HashMap named sites. Note this line:

sites.putIfAbsent(2, "Wiki");

The key 2 already exists in sites, so no insertion is performed.

Java HashMap

❮ Java String Replaceall Exception Chain ❯