![]() |
VOOZH | about |
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.
Original map: {1=Geek1, 2=Geek2, 3=Geek3}
Replaced value: Geek2
Updated map: {1=Geek1, 2=Geek10, 3=Geek3}
public V replace(K key, V newValue)
Parameters:
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.
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.
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().
Original map: {1=Geek1, 3=Geek3}
Replaced value: Geek3
Updated map: {1=Geek1, 3=Geek30}