March 5, 2010

Groovy Goodness: Intersect Collections

In Groovy we have a lot of useful methods to work with collections and lists. For example if we have two lists and want to determine which elements are in both lists, we can use the intersect() method. We can use the disjoint() to test if both collections contain common elements are not.

def one = ['Java', 'Groovy', 'Scala']
def two = ['Groovy', 'JRuby', 'Java']
def three = ['C++', 'C##']

assert ['Groovy', 'Java'] == one.intersect(two)
assert [] == one.intersect(three)
assert one.disjoint(three)
assert !one.disjoint(two)