Search code examples
javacollectionsenumsenumset

Check enumsets for same enum values


I have two EnumSets.

EnumSet.of(A1, A2, A3);
EnumSet.of(A3, A4, A5, A6);

I want to find which values exist in both sets. (In that case, A3.)

Is there any quick way to do that?


Solution

  • EnumSet is a Set. So you can probably use retainAll method to get the intersection.

    Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

    Note that this will modify the existing collection. If you don't want that, you can create a copy. If that's not a good option for you, you can look for other solutions.