Check if a particular value exists in HashMap with Example

In the last tutorial I have shared how to check if a particular key exists in  HashMap or not. In this tutorial we will see how to check if a particular value exists in HashMap or not. We will be using containsValue() method of HashMap class to perform this check.

Syntax :

public boolean containsValue(Object value) : According to Oracle docs, returns true if the Map maps one or more keys to the specified value.

Check if a particular value exists in HashMap Example :

Here we have a HashMap of Integer keys and String values, we are checking whether any of the key in HashMap mapped to a particular String value.



import java.util.*;

 public class ExampleToCheckValue {
    public static void main(String args[]) {
        
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
 
    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Apple");
    hashmap.put(22,"Banana");
    hashmap.put(33,"Mango");
    hashmap.put(44,"Pear");
    hashmap.put(55,"PineApple");
 
    // Checking Value Existence
    boolean flag = hashmap.containsValue("Mango");
    System.out.println("String Mango exists in HashMap? : " + flag);
 
    boolean flag2 = hashmap.containsValue("Grapes");
    System.out.println("String Grapes exists in HashMap? : " + flag2);
 
    }
}


Output
String Mango exists in HashMap? : true
String Grapes exists in HashMap? : false



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry