Java Program to check if a particular key exists in TreeMap


To check if a particular key exists in TreeMap, use the containsKey() method.

Create a TreeMap first and add some elements −

TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"PHP");
m.put(2,"jQuery");
m.put(3,"JavaScript");
m.put(4,"Ruby");
m.put(5,"Java");
m.put(6,"AngularJS");
m.put(7,"ExpressJS");

Now, let’s say we need to check that key 5 exists or not. For that, set the containsKey() method like this −

m.containsKey(5)

The following is an example to check if a particular key exists in TreeMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"PHP");
      m.put(2,"jQuery");
      m.put(3,"JavaScript");
      m.put(4,"Ruby");
      m.put(5,"Java");
      m.put(6,"AngularJS");
      m.put(7,"ExpressJS");
      System.out.println("TreeMap Elements...
"+m);       System.out.println("Does key 5 exist in the TreeMap = "+m.containsKey(5));    } }

Output

TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Does key 5 exist in the TreeMap = true

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements