Search a key in treemap in java

We can use containsKey() method to search a key in treemap in java.

containsKey(Object k): Returns true if this map contains specified key otherwise returns false.

Syntax:

public boolean containsKey(Object k)

Example

package com.w3spoint;
 
import java.util.TreeMap;
 
public class Test {
  public static void main(String args[]){
	//Create TreeMap object.
	TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
 
	//Add objects to the TreeMap.
	treeMap.put(4, "Roxy");
	treeMap.put(2, "Sunil");
	treeMap.put(5, "Sandy");
	treeMap.put(1, "Munish");
	treeMap.put(3, "Pardeep");
 
	//Print the TreeMap object.
	System.out.println("TreeMap elements:");
	System.out.println(treeMap);
 
	if(treeMap.containsKey(3)){
            System.out.println("The TreeMap contains key 3");
        } else {
            System.out.println("The TreeMap does not contains key 3");
        }
  }
}

Output

TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
The TreeMap contains key 3
Please follow and like us:
Content Protection by DMCA.com