Check If Value Exists in HashMap Java Example

This Java example shows how to check if the HashMap object contains a particular value using the containsValue() method of HashMap class.

containsValue(Object value)

This method returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface.
Map<String, String> userCityMapping = new HashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Ramesh", "Pune");
userCityMapping.put("Steve", "London");

// Check if a value exists in a HashMap
if(userCityMapping.containsValue("New York")) {
     System.out.println("There is a user in the userCityMapping who lives in New York");
} else {
     System.out.println("There is not user in the userCityMapping who lives in New York");
}

Complete Example

import java.util.LinkedHashMap;
import java.util.Map;

public class AccessKeysFromHashMapExample {
    public static void main(String[] args) {
        Map<String, String> userCityMapping = new LinkedHashMap<String, String>();

        // Check if a HashMap is empty
        System.out.println("is userCityMapping empty? : " + userCityMapping.isEmpty());

        userCityMapping.put("John", "New York");
        userCityMapping.put("Ramesh", "Pune");
        userCityMapping.put("Steve", "London");

        System.out.println("userCityMapping HashMap : " + userCityMapping);

        // Find the size of a HashMap
        System.out.println("We have the city information of " + userCityMapping.size() + " users");

        // Check if a value exists in a HashMap
        if(userCityMapping.containsValue("New York")) {
            System.out.println("There is a user in the userCityMapping who lives in New York");
        } else {
            System.out.println("There is not user in the userCityMapping who lives in New York");
        }
    }
}

Output

is userCityMapping empty? : true
userCityMapping HashMap : {John=New York, Ramesh=Pune, Steve=London}
We have the city information of 3 users
There is a user in the userCityMapping who lives in New York

Reference


Comments