16

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 = ?

Alex Spurling
  • 54,094
  • 23
  • 70
  • 76

3 Answers3

25

An EnumSet is also a collection, so you can use many of the Collection API calls as well, such as addAll.

EnumSet<Suit> redAndBlack = EnumSet.copyOf(reds);
redAndBlack.addAll(blacks);
tschaible
  • 7,635
  • 1
  • 31
  • 34
3

In this case, you could also use

EnumSet<Suit> redAndBlack = EnumSet.allOf(Suit.class)
noelob
  • 460
  • 5
  • 14
  • 2
    This is correct, answers the question, and may be helpful for some readers. Why has it been downvoted? – Michael Scheper Jan 10 '14 at 02:43
  • 1
    @MichaelScheper : This isn't the union of the two sets, it is the original set. In this case they are equivalent, but you are right. If I had to guess I would say that the reason for this being downvoted is because this is what pops up when you search java enum union. – Jpatrick Nov 07 '16 at 20:57
  • 1
    @Jpatrick: :nod: It seems vindictive and silly to punish somebody for answering the OP's question, when it's different from what they wished was asked. But it's been made clear in the last 24 hours how many haters there are in the world, so I shouldn't be surprised. – Michael Scheper Nov 09 '16 at 20:02
  • 1
    @MichaelScheper you're seeing malice where there is none. This answer is not the correct answer to the question I asked. Just because it gives the same result for the example given, does not mean that it will give the same result in all cases. That does not mean the answer is not useful or worthwhile, just that it answers the wrong question. I can keep the answer here because others might find it useful but it should not get many upvotes lest someone come and blindly copy the solution without realising it doesn't actually solve the problem I stated. – Alex Spurling Apr 30 '21 at 12:35
2

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;
}
James Paterson
  • 2,652
  • 3
  • 27
  • 40