Java Map containsValue() example

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

1. Map containsValue() Method Overview

Definition:

The containsValue() method of the Java Map interface is used to check if the map contains one or more keys mapped to the specified value.

Syntax:

boolean result = map.containsValue(Object value);

Parameters:

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

Key Points:

- The method returns true if the map contains one or more keys mapped to the specified value; otherwise, it returns false.

- The method can accept null as a value. If the map contains one or more keys mapped to a null value, then this method will return true.

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

- Unlike containsKey(), which checks the presence of a key, the containsValue() method checks the presence of a specific value across all the key-value pairs in the map.

2. Map containsValue() Method Example

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

public class MapContainsValueExample {
    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("Cherry", "Red");
        fruitColors.put("Pear", null);

        // Check if values are present
        System.out.println(fruitColors.containsValue("Red"));     // true
        System.out.println(fruitColors.containsValue("Blue"));    // false
        System.out.println(fruitColors.containsValue(null));      // true
    }
}

Output:

true
false
true

Explanation:

In this example:

1. We create a HashMap and populate it with key-value pairs. Among them, "Apple" and "Cherry" share the same value "Red", and "Pear" has a null value.

2. We then use the containsValue() method to check the presence of various values:

- Checking for "Red" returns true as two fruits ("Apple" and "Cherry") have the color "Red".

- Checking for "Blue" returns false since no fruit in the map has this color.

- Checking for a null value returns true as "Pear" has a null value.

The containsValue() method is beneficial when you want to verify if a certain value exists in the map, irrespective of the key it's associated with.

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

Comments