Java TreeMap containsKey(Object key) Method Example

The containsKey(Object key) method of java.util.TreeMap class returns true if this map contains a mapping for the specified key.

Signature

public boolean containsKey(Object key)

This method returns true if this map contains a mapping for the specified key.

Example

The following example shows the usage of java.util.TreeMap.containsKey(key) method.

import java.util.TreeMap;

public class ContainsKeyMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to put elements to the TreeMap
        treeMap1.put(1,"Element1");
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //Check if the treeMap1 contains key "2"
        System.out.println("Does \"treeMap1\" contains key \"2\" : "+treeMap1.containsKey(2));
    }
}

Output

Does "treeMap1" contains key "2" : true

Leave a Reply

Your email address will not be published. Required fields are marked *