Java TreeMap - containsKey() Method
The java.util.TreeMap.containsKey() method returns true if this map contains a mapping for the specified key.
Syntax
public boolean containsKey(Object key)
Parameters
key |
Specify the key whose presence in this map is to be tested. |
Return Value
Returns true if this map contains a mapping for the specified key.
Exception
- Throws ClassCastException, if the specified key cannot be compared with the keys currently in the map.
- Throws NullPointerException, if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
Example:
In the example below, the java.util.TreeMap.containsKey() method is used to check the presence of specified key in the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treemap TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>(); //populating MyMap MyMap.put(102, "John"); MyMap.put(103, "Marry"); MyMap.put(101, "Kim"); MyMap.put(104, "Jo"); //check the presence of 103 key System.out.print("Does MyMap contain 103 key? - "); System.out.print(MyMap.containsKey(103)); //check the presence of 105 key System.out.print("\nDoes MyMap contain 105 key? - "); System.out.print(MyMap.containsKey(105)); } }
The output of the above code will be:
Does MyMap contain 103 key? - true Does MyMap contain 105 key? - false
❮ Java.util - TreeMap