Opposite of intersect in groovy collections

老子叫甜甜 提交于 2019-12-23 06:49:10

问题


what would be the opposite of intersect in groovy collections?


回答1:


You probably want to combine both the answers from @Andre and @denis

I think what you want is the union and then subtract the intersection from this

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

assert [1,5] == ( a + b ) - a.intersect( b )

The solution given by denis would depend on whether you do

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

or

def opposite = rightCollection-leftCollection // []

which I don't think you wanted




回答2:


I'm not certain what you mean by "opposite of union", but my guess is that you mean symmetric difference (AKA set difference or disjunction). The result of this operation is shown in red below.

The easiest way to perform this operation on two Java/Groovy collections is to use the disjunction method provided by Apache commons collections.




回答3:


Could it be this?

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

Prints

[1,5]



回答4:


use intersect for intersections

assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])

use + for unions:

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

see http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html




回答5:


(a-b)+(b-a)
// (a-b) return [1,5]
//(b-a) return []
// TOTAL = [1,5]+[]

this is when we have: a=[1,2,3,4,5],b=[2,3,4,5]

OOP :

java.util.List.metaClass.oppIntersect={b->
  return ((delegate-b)+(b-delegate))
}

then

a.oppIntersect(b)

END!



来源:https://stackoverflow.com/questions/5713665/opposite-of-intersect-in-groovy-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!