views:

1020

answers:

5

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?

+1  A: 

check out the sets api. if you use addAll you can get or. If you use retainAll you can get the and. I dont know about the Xor.

Edit: from the set documentation.

...If the specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets.

....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.

Milhous
Wouldn't [xor] be combination of [starting set - or]?
Esko
+3  A: 

@Milhous said:

check out the sets api. if you use addAll you can get or. If you use retainAll you can get the and. I dont know about the Xor.

It seems like if you had sets s1 and s2 you could do this to get XOR:

  1. copy the set s1 to s3
  2. s1.removeAll(s2); (s1 now contains all elements not in s2)
  3. s2.removeAll(s3); (s2 now contains all elements not in s3 = the old s1)
  4. s1.addAll(s2); (s1 now contains the union of the above two sets)
Jason S
+17  A: 

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.

argonide
The tutorial discussion on sets at http://java.sun.com/docs/books/tutorial/collections/interfaces/set.html may also be helpful background.
joel.neely
A: 

I'm pretty sure that Jakarta Common Collections API supports unions, intersections etc.

I'd be amazed if the Google Collections API didn't as well.

Fortyrunner
Sadly, the Commons Collections Lib doesn't offer generics.
ivan_ivanovich_ivanoff
+2  A: 

You can use the Google-Collections Sets class which has the methods intersection() union() and difference(). See this blog entry for examples: Preconditions, Multimaps and partitioning with Google Collections

axelclk
It should it emphasized that the views (offered by the google collections) are a far more efficient approach to performing set operations when you have large sets. This is especially true if you don't need to iterate through all the elements in the result; you are using it as logical construct in the middle of a more complex algorithm. Have a look at http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Sets.html#union%28java.util.Set,%20java.util.Set%29 for example.
Dilum Ranatunga