Easy Tutorial
❮ Java9 New Features Net Url ❯

Java HashMap containsKey() Method

Java HashMap

The containsKey() method checks if the hashMap contains a mapping for the specified key.

The syntax for the containsKey() method is:

hashmap.containsKey(Object key)

Note: hashmap is an object of the HashMap class.

Parameter:

Return Value

Returns true if the hashMap contains a mapping for the specified key, otherwise returns false.

Example

The following example demonstrates the use of the containsKey() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Check if key 1 exists
        if(sites.containsKey(1)) {
            System.out.println("Key 1 exists in sites");
        }
    }
}

Output:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Key 1 exists in sites

For non-existing keys, we can perform an insert operation.

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Check if key 4 exists, if not, insert the key/value pair
        if(!sites.containsKey(4)) {
            sites.put(4, "Wiki");
        }
        System.out.println("Updated sites HashMap: " + sites);
    }
}

Output:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Updated sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao, 4=Wiki}

Note: We can also achieve the same result using the HashMap putIfAbsent() method.

Java HashMap

❮ Java9 New Features Net Url ❯