Open In App

Java TreeMap get() Method

Last Updated : 16 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The get() method of the TreeMap class in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. If the key does not exist in the map, the method returns null.

Syntax of TreeMap get() Method

treeMap.get(Object key)

  • Parameter: key: The method takes one parameter "key" of object type, and refers to the key whose associated value is supposed to be fetched. 
  • Returns: The method returns the value associated with the "key" in the parameter, or null if no mapping exists for the key.

Examples of Java TreeMap get() Method

Example 1: In this example, we are going to create a TreeMap with integer keys and string values, and then we will fetch the values for specific keys using the get() method.

Java
// Java program to demonstrate 
// the get() method of TreeMap
import java.util.*;

public class Geeks {
    
    public static void main(String[] args) {

        // Create an empty TreeMap
        TreeMap<Integer, String> tm = new TreeMap<Integer, String>();

        // Map string values to int keys
        tm.put(10, "Geeks");
        tm.put(15, "4");
        tm.put(20, "Geeks");
        tm.put(25, "Welcomes");
        tm.put(30, "You");

        System.out.println("Initial mapping: " + tm);

        // Get the value of key 25
        System.out.println("The Value is: " + tm.get(25));

        // Get the value of key 10
        System.out.println("The Value is: " + tm.get(10));
    }
}

Output
Initial mapping: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The Value is: Welcomes
The Value is: Geeks


Example 2: In this example, we are going to create a TreeMap with string keys and integer values.

Java
// Java program to demonstrate 
// the get() method of TreeMap
import java.util.*;

public class Geeks {
    public static void main(String[] args) {

        // Create an empty TreeMap
        TreeMap<String, Integer> tm = new TreeMap<String, Integer>();

        // Map int values to string keys
        tm.put("Geeks", 10);
        tm.put("4", 15);
        tm.put("Geeks", 20); 
        tm.put("Welcomes", 25);
        tm.put("You", 30);

        System.out.println("Initial Mapping: " + tm);

        System.out.println("The Value is: " + tm.get("Geeks"));

        System.out.println("The Value is: " + tm.get("You"));
    }
}

Output
Initial Mapping: {4=15, Geeks=20, Welcomes=25, You=30}
The Value is: 20
The Value is: 30


Important Points:

  • If the key does not exist, get() method returns null.
  • The duplicate keys will be overridden means only the latest value is retained.
  • The treeMap stores keys in natural sorted order i.e. ascending for numbers, alphabetical for strings.
  • The get() method can be used with any object types as long as the keys implement Comparable.

Next Article

Similar Reads