How to check whether a particular key is present in HashMap

In this article, we will discuss how to check whether a key is present in the invoking HashMap or Not

 

HashMap :

  • Same example can be used to search for any particular key in LinkedHashMap and TreeMap

 

Searching a key from HashMap :

Method signature: boolean containsKey(Object key);

boolean containsKey(Object key);
  • This method is used to search specified key from invoking Map object;
  • it can be HashMap or LinkedHashMap or TreeMap
  • Returns true, if key is present;
  • otherwise return false

SearchSpecifiedKeyFromHashMap.java

package in.bench.resources.java.map;

import java.util.HashMap;

public class SearchSpecifiedKeyFromHashMap {

	public static void main(String[] args) {

		// creating HashMap object of type <String, String>
		HashMap<String, String> hashMap = new HashMap<String, String>(); 

		// adding key-value pairs to HashMap object
		hashMap.put("Google", "Sundar Pichai");
		hashMap.put("Facebook", "Mark Zuckerberg");
		hashMap.put("LinkedIn", "Reid Hoffman");
		hashMap.put("Apple", "Steve Jobs");
		hashMap.put("Microsoft", "Bill Gates");

		// printing all Key-Value pairs
		System.out.println("all Key-Value pairs:\n\n" + hashMap);

		// search for key
		boolean searchKey = hashMap.containsKey("Apple");

		System.out.println("\n\nWhether key 'Apple' is present in "
				+ "hashMap ? " + searchKey);

		// testing & printing in same line
		System.out.println("\n\nWhether key 'Facebook' is present in "
				+ "hashMap ? " + hashMap.containsKey("Facebook"));

		System.out.println("\n\nWhether key 'Whatsup' is present in "
				+ "hashMap ? " + hashMap.containsKey("Whatsup"));
	}
}

Output:

all Key-Value pairs:

{LinkedIn=Reid Hoffman, Apple=Steve Jobs, Google=Sundar Pichai, 
Microsoft=Bill Gates, Facebook=Mark Zuckerberg}


Whether key 'Apple' is present in hashMap ? true


Whether key 'Facebook' is present in hashMap ? true


Whether key 'Whatsup' is present in hashMap ? false

 

References:

 

Happy Coding !!
Happy Learning !!

How to check whether a particular value is present in HashMap
How to delete all entries of HashMap