What is the EnumSet.containsAll method in Java?
EnumSetis similar toSet, exceptEnumSetonly contains theEnumtype as elements. Also, all the elements must be from a singleEnumtype. 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
EnumSetandArrayListclasses. -
Line 4: We create an
Enumwith the nameSize. -
Lines 8 and 9: We create a new
EnumSetobject using theofmethod. We passSize.SMALLandSize.MEDIUMas an argument to theof()method. Theof()method will return anEnumSetobject that containsSize.SMALLandSize.MEDIUMEnumelements. -
Line 10: We create a new
ArrayListobject with the namelist1and add theSize.SMALLandSize.MEDIUMelement to it. -
Line 16: We use the
containsAll()method to check if all elements oflist1are present in theset. In this case,trueis returned because all the elements oflist1are present in theset. -
Line 18: We create a new
ArrayListobject with the namelist2and add theSize.LARGEelement to it. -
Line 22: We use the
containsAll()method to check if all elements oflist2are present in theset. In this case,falseis returned because the elementSize.LARGEoflist2is not present in theset.