How to Search key in HashMap Java?

HashMap.containsKey()  method is used to check a key exits or not in hashmap. HashMap.containsKey() Method returns true if this map contains a mapping for the given key. More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)).
(There can be at most one such mapping.)

Syntax :

public boolean containsKey(Object key) {

}

Parameters – key key whose presence in this map is to be tested
Return Value – true if this map contains a mapping for the given key
Exception – Its throws following exception
ClassCastException – if the key is of an inappropriate type for this map (optional)
NullPointerException – if the specified key is null and this map does not permit null keys (optional)

import java.util.HashMap;
import java.util.Map;

public class HashMapSearchKey {
public static void main(String[] args) {

Map<Integer,String> hm = new HashMap<Integer,String>();

/*
* Associates the specified value with the specified key in
this map (optional operation). If the map previously
contained a mapping for the key, the old value is
replaced by the specified value
*/
hm.put(1,"ankush");
hm.put(2, "amit");
hm.put(3,"shivam");
hm.put(4,"ankit");
hm.put(5, "yogesh");

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

System.out.println("key  1   ="+hm.containsKey(1));
System.out.println("key  20  ="+hm.containsKey(20));
System.out.println("key 9    ="+hm.containsKey(9));
System.out.println("key  5   ="+ hm.containsKey(5));

}
}

Output:

key  1   =true

key  20  =false

key 9    =false

key  5   =true

A Guide To HashMap

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 50 = 54