Combining Java EnumSets

Viewed 11783

If I have an Enum, I can create an EnumSet using the handy EnumSet class

enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
EnumSet<Suit> reds = EnumSet.of(Suit.HEARTS, Suit.DIAMONDS);
EnumSet<Suit> blacks = EnumSet.of(Suit.CLUBS, Suit.SPADES);

Give two EnumSets, how can I create a new EnumSet which contains the union of both of those sets?

EnumSet<Suit> redAndBlack = ?

3 Answers

Here's the answer extracted into a generic that you can use with any two EnumSet<T>'s to merge them.

private <T extends Enum<T>> EnumSet<T> mergeEnumSet(EnumSet<T> a, EnumSet<T> b) {
    final EnumSet<T> union = EnumSet.copyOf(a);
    union.addAll(b);
    return union;
}
Related