put(K key, V value) method

put(K key, V value): This method is used to set the value with the corresponding key in TreeMap. If the TreeMap already contained the key, then the old value is replaced by new Value.

put(K key, V value):

Where, K is the key with which the specified value(V) is to be associated in TreeMap.
V is the value to be associated with the specified key(K) in TreeMap.
return NULL, if there was no mapping for key. It returns the previous value if the associated key already present.

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, "SITE");
		
		// Adding element again with same key, So it replace the old value
		System.out.println("It returns previous value = "+ listOfNames.put(1, "HI"));
		
		for(Integer key : listOfNames.keySet())
			System.out.println("Names from list = "+listOfNames.get(key));
	}
}

Output: It returns previous value = JAVA
Names from list = HI
Names from list = GOAL
Names from list = SITE

Leave a Comment