VOOZH about

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

⇱ Java HashMap replace(key, oldValue, newValue) Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java HashMap replace(key, oldValue, newValue) Method

Last Updated : 12 Jul, 2025

The replace(key, oldValue, newValue) method of the HashMap class in Java is used to conditionally replace the value of a specified key if, and only if, the current value matches the specified old value.

Example 1: This example demonstrates replacing a value only if the key is mapped to the given old value.


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

Syntax of replace(key, oldValue, newValue) Method

boolean replace(K key, V oldValue, V newValue)

Parameters:

  • key: The key whose associated value is to be replaced.
  • oldValue: The expected current value associated with the key.
  • newValue: The new value to associated with the key.

Return Type:

This method returns "true" if the value associated with the key is replaced successfully or return "false" if the key does not exist in the map.

Exception:

  • NullPointerException occurs only if null is used for a key or value in a map that doesn't support null.
  • IllegalArgumentException only applies to certain Map implementations (like some custom implementations or ConcurrentHashMap).

Example 2: This example shows what happens when the old value provided does not match the current value.


Output
Initial HashMap: {1=Java, 2=C++, 3=Python}
Was replacement successful? false
Updated HashMap: {1=Java, 2=C++, 3=Python}


Example 3: This example demonstrates that if the key does not exists, the method returns false.


Output
Initial HashMap: {1=Java, 2=C++}
Was replacement successful? false
Updated HashMap: {1=Java, 2=C++}
Comment