How to check whether a particular value is present in HashMap

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

 

HashMap :

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

 

Searching a value from HashMap :

Method signature:

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

SearchSpecifiedValueFromHashMap.java

package in.bench.resources.java.map;

import java.util.HashMap;

public class SearchSpecifiedValueFromHashMap {

	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 value
		boolean searchValue = hashMap.containsValue("Bill Gates");

		System.out.println("\n\nWhether value 'Bill Gates' is present in"
				+ " hashMap ? " + searchValue);

		// printing in same line
		System.out.println("\n\nWhether value 'Steve Jobs' is present in"
				+ " hashMap ? " + hashMap.containsValue("Steve Jobs"));

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

Output:

all Key-Value pairs:

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


Whether value 'Bill Gates' is present in hashMap ? true


Whether value 'Steve Jobs' is present in hashMap ? true


Whether key 'Shiv Nadar' is present in hashMap ? false

 

References:

 

Happy Coding !!
Happy Learning !!

Adding one HashMap to another HashMap using putAll method
How to check whether a particular key is present in HashMap