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

replace(K key, V oldValue, V newValue): This method is used to replace the entry for the specified key only if it is currently mapped to some value. If oldValue doesn’t match with associated key then it does not replace the value. Its return type is boolean.

replace(K key, V oldValue, V newValue)

Where, Key is the key with which the specified value(V) is to be associated in TreeMap.
oldValue is the value to be associated with the specified key(K) in TreeMap.
newValue is the value that will be associate with the specified key(K) in TreeMap.

import java.util.TreeMap;

public class ExampleOfTreeMap 
{
	public static void main(String[] args) 
	{
		TreeMap<Integer,String> listOfNames = new TreeMap<Integer, String>();
		
		listOfNames.put(1, "JAVA");
		listOfNames.put(2, "GOAL");
		listOfNames.put(3, "RAVI");
		
		listOfNames.replace(2, "Hello");
		
		System.out.println("Value of key 2 = "+listOfNames.get(2));
		
	}
}

Output: Value of key 2 = Hello

Leave a Comment