Daddy Warbox Daddy Warbox - 1 year ago 61
Java Question

Java: Is there an easy, quick way to AND, OR, or XOR together sets?

That is, if I had two or more sets, and I wanted to return a new set containing either:

  1. All of the elements each set has in common (AND).

  2. All of the elements total of each set (OR).

  3. All of the elements unique to each set. (XOR).

Is there an easy, pre-existing way to do that?

Edit: That's the wrong terminology, isn't it?

Answer Source

Assuming 2 Set objects a and b

AND(intersection of two sets)


OR(union of two sets)


XOR either roll your own loop:

foreach item
if(a.contains(item) and !b.contains(item) ||  (!a.contains(item) and b.contains(item)))

or do this:

a.retainAll(b); //a now has the intersection of a and b

See the Set documentation and this page. For more.