VOOZH about

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

⇱ Java TreeMap containsKey() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java TreeMap containsKey() Method

Last Updated : 11 Jul, 2025

The containsKey() method in Java is used to check if a given key exists in a TreeMap. If the key is present in the map, it returns true, otherwise, it returns false. This method is very helpful when we need to verify whether a mapping exists before performing any operation on it.

Syntax of TreeMap containsKey() Method

treeMap.containsKey(key);

  • Parameter: key: This is the key whose mapping is supposed to be checked inside a map.
  • Return Value: The method returns boolean true if the presence of the key is detected else false.

Examples of the TreeMap containsKey() Method in Java

Example 1: In this example, we are going to use a TreeMap with Integer keys and String values. We will check the presence of keys using the containsKey() method.


Output
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Is the key '20' present? true
Is the key '5' present? false


Example 2: In this example, we are going to create a TreeMap with String keys and Integer values. Here, we will check for the existence of some string keys.


Output
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
Is the key 'Welcomes' present? true
Is the key 'World' present? false


Important Points:

  • This method checks whether a particular key present or not in the map.
  • This method works with all types of keys that is Integer, String, etc.
  • This method is very useful for avoiding NullPointerExceptions or for validating keys before updates.
  • If there are duplicate keys are added, the latest value will overwrite the old one, but the key will still be present.
Comment