what would be the opposite of intersect in groovy collections?
-
This is very similar to This is very similar to http://stackoverflow.com/questions/2544258/how-can-i-compare-two-lists-in-groovy/2549647 (but this question has a better title) – Ted Naleid Apr 20 '11 at 01:35
5 Answers
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

- 167,322
- 27
- 342
- 338
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.

- 185,044
- 174
- 569
- 824
-
Doesn't that just do `( a + b ) - a.intersect( b )` as I put in my answer? Worried my answer is incorrect now... – tim_yates Apr 19 '11 at 14:39
-
2Yes, it does exactly the same as your answer, but I favour using the proven work of others over writing my own inferior untested implementation :) – Dónal Apr 19 '11 at 14:50
-
2No offence meant, I really mean **my own** crappy implementations, not yours :-) – Dónal Apr 19 '11 at 16:57
-
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]

- 11,645
- 2
- 28
- 23
-
2In case, you use minus operator in Groovy, it might led to the weak of performance, according to [link](http://rewoo.wordpress.com/2012/11/19/the-weak-performance-of-the-groovy-minus-operator/) – Phat H. VU Jan 06 '14 at 06:55
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

- 4,381
- 28
- 28
(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!

- 1
- 1

- 87,526
- 38
- 249
- 254