Java TreeMap.containsKey(Object key) example

Java TreeMap.containsKey(Object key) example

By technicalkeeda, Views 375, Date 21-Feb-2018

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.

tags Java

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


public boolean containsKey(Object key)


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


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


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);



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


Hi there! I am founder of and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][]