That is, if I had two or more sets, and I wanted to return a new set containing either:
Is there an easy, pre-existing way to do that?
Edit: That's the wrong terminology, isn't it?
Bitwise XOR (exclusive or) "^" is an operator in Java that provides the answer '1' if both of the bits in its operands are different, if both of the bits are same then the XOR operator gives the result '0'. XOR is a binary operator that is evaluated from left to right.
The reverse of any xor operation is itself, so the reverse of bitxor is bitxor. This is a fundamental property of xor, applying it twice gets you back where you started.
The operator for XNOR is A==B , or !( A^B) . This returns a boolean value.
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.
You can use the Google-Collections Sets class which has the methods intersection() union() and symmetricDifference().
Sets.intersection(set1, set2);
Sets.union(set1, set2);
SetView view = Sets.intersection(Sets.union(set1, set2), set3);
Set result = view.copyInto(new HashSet());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With