Check If Key Exists in HashMap Java Example

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

HashMap.containsKey(Object key) Method

This method returns true if this map contains a mapping for the specified 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.)
Map<String, String> userCityMapping = new HashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Ramesh", "Pune");
userCityMapping.put("Steve", "London");

String userName = "Steve";
// Check if a key exists in the HashMap
if(userCityMapping.containsKey(userName)) {
     // Get the value assigned to a given key in the HashMap
     String city = userCityMapping.get(userName);
     System.out.println(userName + " lives in " + city);
} else {
     System.out.println("City details not found for user " + userName);
}

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");

        String userName = "Steve";
        
        // Check if a key exists in the HashMap
        if(userCityMapping.containsKey(userName)) {
            // Get the value assigned to a given key in the HashMap
            String city = userCityMapping.get(userName);
            System.out.println(userName + " lives in " + city);
        } else {
            System.out.println("City details not found for user " + userName);
        }
    }
}

Output

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

Reference



Related HashMap Source Code Examples


Comments