Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 449
Daddy Warbox Avatar asked Dec 26 '08 16:12

Daddy Warbox


People also ask

What is Bitwise exclusive or in Java?

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.

What is the opposite of XOR?

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.

How do you write Xnor in Java?

The operator for XNOR is A==B , or !( A^B) . This returns a boolean value.


2 Answers

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.

like image 133
Ari Ronen Avatar answered Sep 24 '22 12:09

Ari Ronen


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());
like image 38
axelclk Avatar answered Sep 24 '22 12:09

axelclk