Search a key in hashmap in java

We can use containsKey() method to search a key in hashmap 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.w3schools;
 
import java.util.HashMap;
 
public class Test {
  public static void main(String args[]){
	//Create HashMap object.
	HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
 
	//Add objects to the HashSet.
	hashMap.put(4, "Roxy");
	hashMap.put(2, "Sunil");
	hashMap.put(5, "Sandy");
	hashMap.put(1, "Munish");
	hashMap.put(3, "Pardeep");
 
	//Print the HashMap object.
	System.out.println("HashMap elements:");
	System.out.println(hashMap);
 
	if(hashMap.containsKey(4)){
            System.out.println("Hashmap contains key 4");
        } else {
            System.out.println("Hashmap does not contains key 4");
        }
  }
}

Output

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
Hashmap contains key 4