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 EnumSet refer 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 EnumSet and ArrayList class.

  • In line 4, we created an Enum with the name Size.

  • In line 8, we created a new EnumSet object using the of method. We passed Size.SMALL and Size.MEDIUM as an argument to the of method. The of method will return an EnumSet object that contains the Size.SMALL and Size.MEDIUM Enum elements.

  • In line 10, we created a new ArrayList object and added the Size.SMALL and Size.LARGE elements to the list.

  • In line 14, we used the retainAll method to retain only elements that are present in the list. In our case, the elements of the list and set are:

Elements of list -- SMALL, LARGE
Elements of set -- SMALL,MEDIUM

retainAll will do the following:

  • Check if the Enum element SMALL of set is present in the list. The list contains SMALL. So, SMALL is retained in the set.
  • Check if the Enum element MEDIUM of set is present in the list. The list doesn’t contain the Enum MEDIUM. So, the Enum MEDIUM is removed from the set.

The resulting set will be [SMALL].

Free Resources