Java:有没有一种简单、快速的方法来对集合进行 AND、OR 或 XOR? [英] Java: Is there an easy, quick way to AND, OR, or XOR together sets?
本文介绍了Java:有没有一种简单、快速的方法来对集合进行 AND、OR 或 XOR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也就是说,如果我有两个或更多集合,并且我想返回一个新集合,其中包含:
That is, if I had two or more sets, and I wanted to return a new set containing either:
- 每组的所有元素都有共同点 (AND).
- 每个集合的所有元素的总和 (OR).
- 每个集合独有的所有元素.(XOR).
有没有一种简单的、预先存在的方法来做到这一点?
Is there an easy, pre-existing way to do that?
这是错误的术语,不是吗?
That's the wrong terminology, isn't it?
推荐答案
假设 2 设置对象 a 和 b
Assuming 2 Set objects a and b
AND(两个集合的交集)
AND(intersection of two sets)
a.retainAll(b);
OR(两个集合的并集)
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)
或者这样做:
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.
这篇关于Java:有没有一种简单、快速的方法来对集合进行 AND、OR 或 XOR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文