Java TreeMap containsKey() Method
Last Updated :
16 May, 2025
Improve
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.
// Java program to demonstrate
// TreeMap containsKey() method
import java.util.TreeMap;
public class Geeks {
public static void main(String[] args) {
// Create a TreeMap with Integer keys
TreeMap<Integer, String> tm = new TreeMap<>();
// Add key-value pairs
tm.put(10, "Geeks");
tm.put(15, "4");
tm.put(20, "Geeks");
tm.put(25, "Welcomes");
tm.put(30, "You");
System.out.println("Initial Mappings are: " + tm);
// Check if key 20 is present
System.out.println("Is the key '20' present? "
+ tm.containsKey(20));
// Check if key 5 is present
System.out.println("Is the key '5' present? "
+ tm.containsKey(5));
}
}
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.
// Java program to demonstrate
// TreeMap containsKey() method
import java.util.TreeMap;
public class Geeks {
public static void main(String[] args) {
// Create a TreeMap with String keys
TreeMap<String, Integer> tm = new TreeMap<>();
// Add key-value pairs
tm.put("Geeks", 10);
tm.put("4", 15);
tm.put("Geeks", 20);
tm.put("Welcomes", 25);
tm.put("You", 30);
System.out.println("Initial Mappings are: " + tm);
// Check if key is present
System.out.println("Is the key 'Welcomes' present? "
+ tm.containsKey("Welcomes"));
System.out.println("Is the key 'World' present? "
+ tm.containsKey("World"));
}
}
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.