What is the EnumSet.retainAll method in Java?
EnumSet is similar to Set except that EnumSet only contains the Enum type as elements. All the elements must be from a single Enum type.
For further details on
EnumSetrefer here.
The retainAll method removes all the Enum elements of the EnumSet object thatare not present in the passed collection.
Syntax
boolean retainAll(Collection<?> c)
Parameters
This method takes the collection object to be retained in this EnumSet object as an argument.
Return value
This method returns true if the set changed as a result of the call; any element is removed from the set due to the element not being present in the collection. Otherwise, false will be returned.
Code
import java.util.EnumSet;import java.util.ArrayList;class RetainAll {enum Size {SMALL, MEDIUM, LARGE, EXTRALARGE}public static void main( String args[] ) {EnumSet<Size> set = EnumSet.of(Size.SMALL, Size.MEDIUM);ArrayList<Size> list = new ArrayList<>();list.add(Size.SMALL);list.add(Size.LARGE);System.out.println("The set is "+ set);System.out.println("The list is "+ list);System.out.println("\nCalling set.retainAll(list). Is set changed - " + set.retainAll(list));System.out.println("\nThe set is "+ set);}}
Explanation
In the code above:
-
In lines 1 and 2, we imported the
EnumSetandArrayListclass. -
In line 4, we created an
Enumwith the nameSize. -
In line 8, we created a new
EnumSetobject using theofmethod. We passedSize.SMALLandSize.MEDIUMas an argument to theofmethod. Theofmethod will return anEnumSetobject that contains theSize.SMALLandSize.MEDIUMEnum elements. -
In line 10, we created a new
ArrayListobject and added theSize.SMALLandSize.LARGEelements to thelist. -
In line 14, we used the
retainAllmethod to retain only elements that are present in thelist. In our case, the elements of thelistand set are:
Elements of list -- SMALL, LARGE
Elements of set -- SMALL,MEDIUM
retainAll will do the following:
- Check if the Enum element
SMALLofsetis present in thelist. ThelistcontainsSMALL. So,SMALLis retained in theset. - Check if the Enum element
MEDIUMofsetis present in thelist. Thelistdoesn’t contain the EnumMEDIUM. So, the EnumMEDIUMis removed from theset.
The resulting set will be [SMALL].