What is the EnumSet.containsAll method in Java?

EnumSet is similar to Set, except EnumSet only contains the Enum type as elements. Also, all the elements must be from a single Enum type. For further details, click here.

The containsAll() method will check if all the Enum elements of the passed collection are present in the EnumSet object.

Syntax

boolean containsAll(Collection<?> c)

This method takes the collection to be checked, to see if it is present in this set.

Return

This method returns true if all the Enum elements of the passed collection are present in the EnumSet object, otherwise, it returns false.

Code

Let’s look at the code below.

import java.util.EnumSet;
import java.util.ArrayList;
class containsAll {
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
public static void main( String args[] ) {
EnumSet<Size> set = EnumSet.of(Size.SMALL, Size.MEDIUM);
ArrayList<Size> list1 = new ArrayList<>();
list1.add(Size.SMALL);
list1.add(Size.MEDIUM);
System.out.println("The set is "+ set);
System.out.println("list1 is "+ list1);
System.out.println("\nIf set contains list1 is "+ set.containsAll(list1));
ArrayList<Size> list2 = new ArrayList<>();
list2.add(Size.LARGE);
System.out.println("\nlist2 is "+ list2);
System.out.println("If set contains list2 is "+ set.containsAll(list2));
}
}

In the above code, we see the following:

  • Lines 1 and 2: We import the EnumSet and ArrayList classes.

  • Line 4: We create an Enum with the name Size.

  • Lines 8 and 9: We create a new EnumSet object using the of method. We pass Size.SMALL and Size.MEDIUM as an argument to the of() method. The of() method will return an EnumSet object that contains Size.SMALL and Size.MEDIUM Enum elements.

  • Line 10: We create a new ArrayList object with the name list1 and add the Size.SMALL and Size.MEDIUM element to it.

  • Line 16: We use the containsAll() method to check if all elements of list1 are present in the set. In this case, true is returned because all the elements of list1 are present in the set.

  • Line 18: We create a new ArrayList object with the name list2 and add the Size.LARGE element to it.

  • Line 22: We use the containsAll() method to check if all elements of list2 are present in the set. In this case, false is returned because the element Size.LARGE of list2 is not present in the set.

Free Resources