VOOZH about

URL: https://www.geeksforgeeks.org/java/java-treemap-get-method/

⇱ Java TreeMap get() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java TreeMap get() Method

Last Updated : 11 Jul, 2025

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.


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.


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.
Comment