8

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?

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
gts13
  • 1,048
  • 1
  • 16
  • 29

4 Answers4

9

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.

Swapnil
  • 8,201
  • 4
  • 38
  • 57
  • that returns a boolean. I want to know the common element – gts13 Jul 28 '14 at 13:19
  • 4
    If you look at that method carefully, it *modifies* the set and the boolean return value that you get just tells you whether the set changed after this method call. – Swapnil Jul 28 '14 at 13:21
8
EnumSet A = EnumSet.of(A1, A2, A3);
EnumSet B = EnumSet.of(A3, A4, A5, A6);

EnumSet intersection = EnumSet.copyOf(A);

intersection.retainAll(B);

retainAll modifies the underlying set so create a copy.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
another_dev
  • 195
  • 6
7

Since EnumSets are subtypes of Iterable, you can use CollectionUtils from Apaches Collections (often used third party library) for that.

CollectionUtils.intersection (
    EnumSet.of (A1, A2, A3), 
    EnumSet.of (A3, A4, A5, A6)
);
F. Böller
  • 4,194
  • 2
  • 20
  • 32
  • 7
    This question is not a good reason to add a dependency on a third-party library, considering how easily the problem can be addressed using existing Java SE classes. – VGR Jul 28 '14 at 14:09
6

You can use the Streams API in java 8:

Set set1 = EnumSet.of(A1, A2, A3); // add type argument to set
Set set2 = EnumSet.of(A3, A4, A5, A6); // add type argument to set
set2.stream().filter(set1::contains).forEach(a -> {
    // Do something with a (it's in both sets)
});
fabian
  • 80,457
  • 12
  • 86
  • 114