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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:有没有一种简单、快速的方法来对集合进行 AND、OR 或 XOR?
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
