The TreeMap.get() method in Java
Overview
The TreeMap.get()
method is used to get values for the key from the TreeMap entries. It returns the value of the key called or returns NULL when such key is not found in the entries on the TreeMap.
Syntax
TreeMap.get( K Key)
Parameter
Key: We need to get the value of this in the entries on TreeMap.
Example
import java.util.*;class GetMethod // create a class{public static void main(String[] args){ // create empty treeMapTreeMap<Integer, String> tm = new TreeMap<Integer, String>();// inserting data/entries in treeMaptm.put(1, "Apple");tm.put(6, "Mango");tm.put(8, "Orange");tm.put(7, "Papaya");tm.put(4, "banana");// Printing the data at given keySystem.out.println("The value for key 8 is: " + tm.get(8));System.out.println("The value for key 2 is: " + tm.get(2));}}
Explanation
-
Line 1: We import the
utilpackage. -
Line 2: We create the class
GetMethod. -
Line 6: We create the empty
TreeMap. -
Line 8–12 : We insert the entries in the
TreeMapusingTreeMap.put()method. -
Line 14: We print that given
keyis found and the value of the key is returned. -
Line 15: We print that the given
keyhas not been found so it returnsNULL.