What is the putIfAbsent method in Java HashMaps?

putIfAbsent() is a built-in method defined in the HashMap class in Java. The class is available in the java.util package.

The following is the method prototype:

public V putIfAbsent(K key, V value)

Functionality

A HashMap is a data structure that stores data in the form of key-value pairs. Each unique key is mapped onto one or more data values.

The putIfAbsent() method is used to insert the given key-value pair into the HashMap if the associated key is not already present or mapped onto a null value.

Its functionality is similar to the put() method of HashMaps, but with the added check described above.

The putIfAbsent() Method

Parameters and return value

The method takes the following as input arguments:

  • key: The key to be inserted into the HashMap.

  • value: The value to be associated with the provided key.

Note: The types of the key and value must match the key-value types of the HashMap.

The putIfAbsent() method may return the following:

  • null in case of successful insertion.

  • The current value associated with the key in case it already exists within the HashMap.

Code

import java.util.HashMap;
public class Main{
public static void main(String args[]){
// Creating a new HashMap
HashMap<Integer, String> hash_map = new HashMap<>();
// Mapping String values to Integer keys
hash_map.put(2, "Edpresso");
hash_map.put(4, "Shots");
hash_map.put(6, "of");
hash_map.put(8, "Dev");
hash_map.put(10, "Knowledge");
// Displaying the HashMap
System.out.println("HashMap: \n" + hash_map);
// Mapping new value to a new key
hash_map.putIfAbsent(3, "Concise");
// Mapping new value to exisiting key
String value = hash_map.putIfAbsent(8, "Developer");
// Printing current value for key
System.out.println("\nCurrent value: \n" + value);
// Displaying the Updated HashMap
System.out.println("\nUpdated HashMap: \n" + hash_map);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved