That is, if I had two or more sets, and I wanted to return a new set containing either:
- All of the elements each set has in common (AND).
- All of the elements total of each set (OR).
- 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?
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.
Assuming 2 Set objects a and b
AND(intersection of two sets)
OR(union of two sets)
XOR either roll your own loop:
or do this:
See the Set documentation and this page. For more.
You can use the Google-Collections Sets class which has the methods intersection() union() and symmetricDifference().
@Milhous said:
It seems like if you had sets
s1
ands2
you could do this to get XOR:s1
tos3
s1.removeAll(s2);
(s1 now contains all elements not in s2)s2.removeAll(s3);
(s2 now contains all elements not in s3 = the old s1)s1.addAll(s2);
(s1 now contains the union of the above two sets)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.