Java TreeMap.containsKey(Object key) example

In this java tutorial, You will learn how to use containsKey(Object key) method of TreeMap class.The containsKey(Object key) method is used to return 'true' if this map contains a mapping for the specified 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.

Returns

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

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.

Java TreeMap containsKey(Object key) example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap, e.g students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.containsKey(2); It will return true as key 2 is exists in mapset.
  • students.containsKey(8); It will return false as key 8 does not exists in mapset.
package com.technicalkeeda;

import java.util.TreeMap;

public class App {
    public static void main(String args[]) {

        TreeMap < Integer, String > students = new TreeMap < Integer, String > ();

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");

        System.out.println("TreeMap values :- " + students);

        System.out.println(students.containsKey(2));
        System.out.println(students.containsKey(8));
    }
}

output

TreeMap values :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}
true
false