Opposite of intersect in groovy collections
Asked Answered
C

5

21

what would be the opposite of intersect in groovy collections?

Ceiling answered 19/4, 2011 at 8:34 Comment(1)
This is very similar to This is very similar to #2544758 (but this question has a better title)Encomium
P
30

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

Plato answered 19/4, 2011 at 10:10 Comment(0)
F
7

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.

enter image description here

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

Fellow answered 19/4, 2011 at 14:2 Comment(4)
Doesn't that just do ( a + b ) - a.intersect( b ) as I put in my answer? Worried my answer is incorrect now...Plato
Yes, it does exactly the same as your answer, but I favour using the proven work of others over writing my own inferior untested implementation :)You
No offence meant, I really mean my own crappy implementations, not yours :-)You
The diagram was very helpful - thanks for taking the time to include it.Holoblastic
F
6

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]
Federalize answered 19/4, 2011 at 8:48 Comment(1)
In case, you use minus operator in Groovy, it might led to the weak of performance, according to linkSolve
S
3

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

Scraperboard answered 19/4, 2011 at 9:34 Comment(0)
V
0
(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!

Vitebsk answered 18/9, 2014 at 8:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.