Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...