Collections groovy集合中intersect的对立面

Collections groovy集合中intersect的对立面,collections,groovy,intersect,Collections,Groovy,Intersect,groovy集合中的intersect有什么相反之处?可能是这样吗 def leftCollection = [1,2,3,4,5] def rightCollection = [2,3,4] def opposite = leftCollection-rightCollection println opposite 印刷品 [1,5] 使用“相交”作为交点 assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8]) 将+用于联合体: assert

groovy集合中的intersect有什么相反之处?

可能是这样吗

def leftCollection = [1,2,3,4,5]
def rightCollection = [2,3,4]
def opposite = leftCollection-rightCollection
println opposite
印刷品

[1,5]

使用“相交”作为交点

assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])
将+用于联合体:

assert [1,2,3,4,5] == [1,2,3] + [4,5]

请参见

您可能希望结合@Andre和@denis的答案

我想你想要的是并集,然后从中减去交集

def a = [1,2,3,4,5]
def b = [2,3,4]

assert [1,5] == ( a + b ) - a.intersect( b )
丹尼斯给出的解决方案将取决于你是否这样做

def opposite = leftCollection-rightCollection // [1,5]


我不知道你说的“并集的对立面”是什么意思,但我猜你指的是对称差分(又称集差分或析取)。此操作的结果在下面以红色显示

在两个Java/Groovy集合上执行此操作的最简单方法是使用apachecommons集合提供的方法

(a-b)+(b-a)
// (a-b) return [1,5]
//(b-a) return []
// TOTAL = [1,5]+[]
这时我们有:
a=[1,2,3,4,5],b=[2,3,4,5]

面向对象: 然后


结束

这不正是我在回答中所说的那样吗?担心我的答案现在不正确……是的,它与您的答案完全相同,但我更喜欢使用他人的经验证的工作,而不是编写我自己的低劣未经测试的实现:)无意冒犯,我的意思是,我真的是指我自己的蹩脚实现,不是你的:-)图表非常有用-感谢你花时间把它包括进来。这非常类似于这非常类似于(但这个问题有一个更好的标题)如果你在Groovy中使用减号运算符,它可能会导致性能下降,根据
(a-b)+(b-a)
// (a-b) return [1,5]
//(b-a) return []
// TOTAL = [1,5]+[]
java.util.List.metaClass.oppIntersect={b->
  return ((delegate-b)+(b-delegate))
}
a.oppIntersect(b)