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

Daddy Warbox picture Daddy Warbox · Dec 26, 2008 · Viewed 9.4k times · Source

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

Ari Ronen picture Ari Ronen · Dec 26, 2008

Assuming 2 Set objects a and b

AND(intersection of two sets)

a.retainAll(b); 

OR(union of two sets)

a.addAll(b);

XOR either roll your own loop:

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

or do this:

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

See the Set documentation and this page. For more.