April 27, 2011

Groovy Goodness: Convert Collection to Set with Only Unique Elements

Since Groovy 1.8 we can convert an array or collection to a Set with only the unique elements of the original array or collection. We use the toSet() method to do this.

def numbers = [1,2,1,4,1,2] as int[]
assert numbers.toSet() == [1,2,4] as Set

def list = ['Groovy', 'Java', 'Grails', 'Groovy']
assert list.toSet() == ['Groovy', 'Java', 'Grails'] as Set