In this shot, we will learn how to use the TreeMap.get()
method in Java.
The TreeMap.get()
method is present in the TreeMap
class inside the java.util
package.
The TreeMap.get()
method is used to obtain the value associated with the given key on the TreeMap
.
If no such key is present in the TreeMap
, the method returns null
.
The syntax of the TreeMap.get()
method is given below:
V TreeMap.get(K key);
The TreeMap.get()
method accepts one parameter:
Key
: The key for which we need to determine the associated value.The TreeMap.get()
method can return one of values mentioned below:
Value
: Returns the value associated with that key.NULL
: If no such key is present in the TreeMap
.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("The value for key = 2 is: " + t1.get(2));System.out.println("The value for key = 11 is: " + t1.get(11));}}
In line 1, we import the required package.
In line 2, we make a Main
class.
In line 4, we make a main()
function.
In line 6, we declare a TreeMap
that consists of keys of type Integer
and values of type String
.
From lines 8 to 12, we use the TreeMap.put()
method to insert values in the TreeMap
.
In line 14, we use the TreeMap.get()
method to get the value for .
In line 15, we use the TreeMap.get()
method to get the value for . This key is not present, so we get the output value as NULL
.
So, this is the way to use the TreeMap.get()
method in Java.