I have two EnumSet
s.
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?
I have two EnumSet
s.
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?
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.
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.
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)
);
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)
});