Opposite of intersect in groovy collections

18,876

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.

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.

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

Share:
18,876
Espen Schulstad
Author by

Espen Schulstad

Updated on June 06, 2022

Comments

  • Espen Schulstad
    Espen Schulstad almost 2 years

    what would be the opposite of intersect in groovy collections?

  • tim_yates
    tim_yates about 13 years
    Doesn't that just do ( a + b ) - a.intersect( b ) as I put in my answer? Worried my answer is incorrect now...
  • Dónal
    Dónal about 13 years
    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 :)
  • Dónal
    Dónal about 13 years
    No offence meant, I really mean my own crappy implementations, not yours :-)
  • Phat H. VU
    Phat H. VU over 10 years
    In case, you use minus operator in Groovy, it might led to the weak of performance, according to link
  • Paul
    Paul almost 8 years
    The diagram was very helpful - thanks for taking the time to include it.