VOOZH about

URL: https://www.geeksforgeeks.org/java/hashmap-putifabsentkey-value-method-in-java-with-examples/

⇱ Java HashMap putIfAbsent() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java HashMap putIfAbsent() Method

Last Updated : 12 Jul, 2025

The putIfAbsent() method of the HashMap class in Java is used to insert a key-value pair into the map only if the key is not present in the map or is mapped to null. The existing value remains unchanged if the key is already associated with a value.

Example 1: In this example, we will demonstrate the basic usage of the putIfAbsent() method.


Output
Before putIfAbsent(): {1=Geek1, 2=Geek2}
After putIfAbsent(): {1=Geek1, 2=Geek2, 3=Geek3}

Explanation: In the above example, the Key 3 is not present, so it gets added with the value "Geek3". The Key 1 already exists, so the value "Geek1" remains unchanged.

Syntax of putIfAbsent() Method

default V putIfAbsent(K key, V value)

V: The return type of the method. It represents the type of the value associated with the key in the HashMap.

Parameters:

  • key: The key with which the specified value is to be associated.
  • value: The value to be associated with the specified key.

Return Type: This method return previous value associated with the specified key or return null if there was no mapping for the key.

Key Points:

  • The method does not overwrite existing mappings.
  • If the key is mapped to null, the new value is inserted.
  • Returns null if the key was absent; otherwise, returns the existing value.

Example 2: In this example, we will see how putIfAbsent() method handles null values and return values.


Output
Original HashMap: {A=100, B=200, C=null}
Result for Key D (absent): null
Result for Key C (null): null
Result for Key A (existing): 100
Updated HashMap: {A=100, B=200, C=300, D=400}

Explanation: In the above example, the Key D is added because it is not present in the map. The Key C is mapped to null, so it is updated with the value 300. The Key A exists with a value of 100, so no change occurs.

Comment