In this shot, we will learn how to use the TreeMap.containsKey()
method in Java, which is present in the TreeMap
class inside the java.util
package.
The TreeMap.containsKey()
method is used to check whether the particular key
is present in the TreeMap
or not.
The syntax of the TreeMap.containsKey()
method is shown below:
boolean containsKey(Object key)
Here, the key
is of the type Object
, as every class is a subclass of Object
.
The TreeMap.containsKey()
method accepts only one parameter, i.e., the key
whose presence needs to be checked in the TreeMap
.
The TreeMap.containsKey()
method returns a boolean
value:
true
: If the key
is present in the TreeMap
.false
: If the key
is not present in the TreeMap
.Let’s have a look at the code:
import java.util.*;class Main{public static void main(String[] args){TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();t1.put(1, "Educative");t1.put(5, "Python");t1.put(2, "Java");t1.put(27, "Learn Coding");t1.put(9, "C++");System.out.println("Key = 5 in TreeMap?: " + t1.containsKey(5));System.out.println("Key = 9 in TreeMap?: " + t1.containsKey(9));System.out.println("Key = 14 in TreeMap?: " + t1.containsKey(14));}}
In line 1, we imported the required package.
In line 2, we made a Main
class.
In line 4, we made a main()
function.
In line 6, we declared a TreeMap
consisting of keys of type Integer
and values of type String
.
From lines 8 to 12, we inserted values in the TreeMap
by using the TreeMap.put()
method.
From lines 14 to 16, we display whether the key passed as argument is present in the TreeMap
or not with a message.
So, this is how to use TreeMap.containsKey()
method in Java to check whether the particular key is present in the TreeMap
or not.