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
EnumMapclass. -
In line 3, we have created an enum for days of the week with the name
Days. -
In line 7, we create an
EnumMapobject with the namemap. -
In line 8, we use the
putmethod to add a mapping{Days.MON="chest"}to themapobject. -
In line 10, we use the
containsValuemethod to check if any key is mapped to the valuechest.trueis returned as a result because in the map, the keyDays.MONis mapped to the valuechest. -
In line 11, we use the
containsValuemethod to check if any key is mapped to the valuearms.falseis returned as a result because no key is mapped to the valuearms.