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() MethodtreeMap.containsKey(key);
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
// 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));
}
}
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
// 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"));
}
}
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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4