TreeMap containsKey() method in java

Let’s learn TreeMap containsKey() method in java.

TreeMap containsKey() method in java

containsKey(Object key) returns true if this map contains a mapping for the specified key.

Syntax:

public boolean containsKey(Object key)

Parameters:

key key whose presence in this map is to be tested.

Throws:

ClassCastException – if the specified key cannot be compared with the keys currently in the map.

NullPointerException – if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

Also read – TreeMap in java

Now let’s see example on TreeMap containsKey(Object key) method.

import java.util.TreeMap;
public class TreeMapContainsKeyMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      // map String values to Integer keys
      tm.put(56, "orange");
      tm.put(62, "indigo");
      tm.put(43, "red");
      tm.put(91, "green");
      tm.put(38, "yellow");
      System.out.println("TreeMap before using containsKey() method: " + tm);
      // check for key element '62'
      System.out.println("Does key '62' present? " + tm.containsKey(62));
      // check for key element '90'
      System.out.println("Does key '90' present? " + tm.containsKey(90));
   }
}


Output:

TreeMap before using containsKey() method: {38=yellow, 43=red, 56=orange, 62=indigo, 91=green}
Does key ’62’ present? true
Does key ’90’ present? false


Now let’s map Integer values to String Keys.

import java.util.TreeMap;
public class TreeMapContainsKeyMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
      // Mapping Integer values to string keys
      tm.put("violet", 18);
      tm.put("red", 12);
      tm.put("violet", 14);
      tm.put("green", 16);
      tm.put("blue", 20);
      System.out.println("Given TreeMap Mappings are: " + tm);
      // check for key element 'green'
      System.out.println("Is key 'green' present? " + tm.containsKey("green"));
      // checking for key element 'yellow'
      System.out.println("Is key 'yellow' present? " + tm.containsKey("yellow"));
   }
}


Output:

Given TreeMap Mappings are: {blue=20, green=16, red=12, violet=14}
Is key ‘green’ present? true
Is key ‘yellow’ present? false