Java Map containsKey() example

In this guide, you will learn about the Map containsKey() method in Java programming and how to use it with an example.

1. Map containsKey() Method Overview


The containsKey() method of the Java Map interface checks if the map contains an entry for the specified key.


boolean result = map.containsKey(Object key);


- key: The key whose presence in the map is to be tested.

Key Points:

- It returns true if the map contains a mapping for the specified key, otherwise, it returns false.

- The method can accept null as a key. If the map contains a mapping for a null key, then this method will return true.

- Some map implementations, like HashMap, allow null keys, while others, like TreeMap, do not.

- This method provides a faster way to check the existence of a key in the map compared to getting the value with the key and checking for null.

2. Map containsKey() Method Example

import java.util.HashMap;
import java.util.Map;

public class MapContainsKeyExample {
    public static void main(String[] args) {
        Map<String, String> fruitColors = new HashMap<>();

        // Populate the map
        fruitColors.put("Apple", "Red");
        fruitColors.put("Banana", "Yellow");
        fruitColors.put(null, "N/A");

        // Check if keys are present
        System.out.println(fruitColors.containsKey("Apple"));   // true
        System.out.println(fruitColors.containsKey("Banana"));  // true
        System.out.println(fruitColors.containsKey("Cherry"));  // false
        System.out.println(fruitColors.containsKey(null));      // true




In this example:

1. We create a HashMap and populate it with three key-value pairs. One of these pairs has a null key.

2. We then use the containsKey() method to check the presence of various keys:

- Checking for "Apple" returns true since it's present in the map.

- Checking for "Banana" also returns true.

- Checking for "Cherry" returns false since it's not in the map.

- Checking for a null key returns true as we have added an entry with a null key.

The containsKey() method offers a convenient way to quickly verify if a key is present in the map without having to retrieve its associated value.

Related Map Interface methods

Java Map put() example
Java Map get() example
Java Map remove() example
Java Map containsKey() example
Java Map containsValue() example
Java Map keySet() example
Java Map values() example
Java Map entrySet() example