VOOZH about

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

⇱ Java HashMap replace() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java HashMap replace() Method

Last Updated : 12 Jul, 2025

The replace() method of the HashMap class in Java is used to replace the value associated with a specific key if the key is already present in the map.

Note: If the key does not exist, the method does nothing and the map remains unchanged.

Example 1: This example demonstrates replacing the value of an existing key in the HashMap.


Output
Original map: {1=Geek1, 2=Geek2, 3=Geek3}
Replaced value: Geek2
Updated map: {1=Geek1, 2=Geek10, 3=Geek3}

Syntax of HashMap replace() Method

public V replace(K key, V newValue)

Parameters:

  • key: The key whose associated value is to be replaced.
  • value: The new value to associate with the specified key.

Return Type: This method returns the old value associated with the key or returns null if the key does not exist in the map.

Example 2: This example demonstrates that if the key does not exist in the HashMap, the replace() method does nothing and returns null.


Output
Original map: {1=Geek1, 4=Geek4}
Replaced value: null
Updated map: {1=Geek1, 4=Geek4}


Example 3: This example demonstrates using the overloaded replace() method to conditionally replace a value only if the existing value matches a specific value.


Output
Original map: {1=Geek1, 2=Geek2}
Was value replaced? true
Updated map: {1=Geek1, 2=Geek10}


Example 4: This example shows checking if a key exists before calling replace().


Output
Original map: {1=Geek1, 3=Geek3}
Replaced value: Geek3
Updated map: {1=Geek1, 3=Geek30}
Comment