与常规集合中的交叉相反

Esp*_*tad 21 collections groovy intersect

什么与groovy集合中的交叉相反?

tim*_*tes 28

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

我认为你想要的是联合,然后从中减去交集

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

assert [1,5] == ( a + b ) - a.intersect( b )
Run Code Online (Sandbox Code Playgroud)

丹尼斯给出的解决方案取决于你是否这样做

def opposite = leftCollection-rightCollection // [1,5]
Run Code Online (Sandbox Code Playgroud)

要么

def opposite = rightCollection-leftCollection // []
Run Code Online (Sandbox Code Playgroud)

我不认为你想要的


den*_*nko 6

会是这个吗?

def leftCollection = [1,2,3,4,5]
def rightCollection = [2,3,4]
def opposite = leftCollection-rightCollection
println opposite
Run Code Online (Sandbox Code Playgroud)

印刷

[1,5]
Run Code Online (Sandbox Code Playgroud)

  • 如果您在 Groovy 中使用减号运算符,可能会导致性能下降,根据[链接](http://rewoo.wordpress.com/2012/11/19/the-weak-performance-of-the -groovy 减号运算符/) (2认同)

Dón*_*nal 6

我不确定你的意思是"与工会相对",但我的猜测是你的意思是对称差异(AKA集差异或分离).此操作的结果在下面以红色显示.

在此输入图像描述

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

  • 哈哈!_哎哟_!;-) (4认同)
  • 是的,它与你的答案完全一样,但我赞成使用其他人的经过验证的工作来编写我自己的低劣未经测试的实现:) (2认同)
  • 没有冒犯的意思,我的意思是我自己的糟糕的实现,而不是你的:-) (2认同)