What is the EnumMap.containsValue() method in Java?

Overview

An EnumMap is similar to a Map except that an EnumMap only takes an enum as a key. Also, all the keys must be from a single enum type. For further details refer here.

The containsValue() method of EnumMap is used to check if one or more key is mapped to the specified value.

Syntax

The syntax of the containsValue() method is given below:


public boolean containsValue(Object value)

Parameters

The value whose presence is to be checked is passed as an argument.

Return value

This method returns true if the value has one or more key mapping. Otherwise, false is returned.

Code

The example below shows how to use the containsValue() method.

import java.util.EnumMap;
class ContainsValue {
enum Days{
MON, TUE, WED, THUR, FRI, SAT, SUN
};
public static void main( String args[] ) {
EnumMap<Days, String> map = new EnumMap<>(Days.class);
map.put(Days.MON, "chest");
System.out.println( "The map is" + map);
System.out.println("Checking if any is mapped to the value 'chest': "+ map.containsValue("chest"));
System.out.println("Checking if any is mapped to the value 'arms': "+ map.containsValue("arms"));
}
}

Explanation

In the above code:

  • In line 1, we import the EnumMap class.

  • In line 3, we have created an enum for days of the week with the name Days.

  • In line 7, we create an EnumMap object with the name map.

  • In line 8, we use the put method to add a mapping {Days.MON="chest"} to the map object.

  • In line 10, we use the containsValue method to check if any key is mapped to the value chest. true is returned as a result because in the map, the key Days.MON is mapped to the value chest.

  • In line 11, we use the containsValue method to check if any key is mapped to the value arms. false is returned as a result because no key is mapped to the value arms.