What is the TreeMap.put() method in Java?
In this shot, we will learn how to use the TreeMap.put() method in Java.
Introduction
The TreeMap.put() method is present in the TreeMap class inside the java.util package.
TreeMap.put() is used to insert the key-value mappings in the TreeMap.
Syntax
The syntax of the TreeMap.put() method is given below:
TreeMap.put(K key, V value);
Parameter
The TreeMap.put() method accepts two parameters:
Key: The key which is to be inserted.Value: The value mapped with that key.
Return
The TreeMap.put() method can return one of the two values mentioned below:
- If an existing key is passed, then the previous value gets returned.
- If a new pair is passed, then
NULLis returned.
Code
Let’s have a look at the code.
import java.util.*;class Main{public static void main(String[] args){TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();t1.put(1, "Let's");t1.put(5, "see");t1.put(2, "TreeMap class");t1.put(27, "methods");t1.put(9, "in java.");System.out.println("Original TreeMap: " + t1);System.out.println(t1.put(27, "Hello"));System.out.println(t1.put(37, "Hello"));System.out.println("Modified TreeMap: " + t1);}}
Explanation:
-
In line 1, we import the required package.
-
In line 2, we made a
Mainclass. -
In line 4, we made a
main()function. -
In line 6, we declare a
TreeMapconsisting of keys of typeIntegerand values of typeString. -
From lines 8-12, we insert values in the
TreeMapby using theTreeMap.put()method. -
In line 14, we print the key-value pairs present in the
TreeMap. -
In lines 16-17, we insert two more key-value pairs. The first key,
27, is already present and gives the output as the previous value for this key. The second key,37, is a new key and hence it gives the value asNULLin the output. -
In line 19, we print the modified tree map.
So, this is how to use the TreeMap.put() method in Java.