Opposite of intersect in groovy collections
Solution 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
Solution 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.
Solution 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]
Solution 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
Espen Schulstad
Updated on June 06, 2022Comments
-
Espen Schulstad almost 2 years
what would be the opposite of intersect in groovy collections?
-
tim_yates about 13 yearsDoesn't that just do
( a + b ) - a.intersect( b )
as I put in my answer? Worried my answer is incorrect now... -
Dónal about 13 yearsYes, 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 about 13 yearsNo offence meant, I really mean my own crappy implementations, not yours :-)
-
Phat H. VU over 10 yearsIn case, you use minus operator in Groovy, it might led to the weak of performance, according to link
-
Paul almost 8 yearsThe diagram was very helpful - thanks for taking the time to include it.