What is the TreeMap.get() method in Java?
In this shot, we will learn how to use the TreeMap.get() method in Java.
Introduction
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.
Syntax
The syntax of the TreeMap.get() method is given below:
V TreeMap.get(K key);
Parameters
The TreeMap.get() method accepts one parameter:
Key: The key for which we need to determine the associated value.
Return 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 theTreeMap.
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("The value for key = 2 is: " + t1.get(2));System.out.println("The value for key = 11 is: " + t1.get(11));}}
Explanation
-
In line 1, we import the required package.
-
In line 2, we make a
Mainclass. -
In line 4, we make a
main()function. -
In line 6, we declare a
TreeMapthat consists of keys of typeIntegerand values of typeString. -
From lines 8 to 12, we use the
TreeMap.put()method to insert values in theTreeMap. -
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 asNULL.
So, this is the way to use the TreeMap.get() method in Java.