且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:有没有一种简单、快速的方法来对集合进行 AND、OR 或 XOR?

更新时间:2023-11-08 20:38:04

假设 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.