开发者

Opposite of intersect in groovy collections

开发者 https://www.devze.com 2023-02-27 03:39 出处:网络
what would be the opposite of intersect i开发者_开发知识库n groovy collections?You probably want to combine both the answers from @Andre and @denis

what would be the opposite of intersect i开发者_开发知识库n groovy collections?


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


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.

Opposite of intersect in groovy collections

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


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]


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


(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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号