Search

Dark theme | Light theme

December 17, 2009

Groovy Goodness: Splitting with Closures

Groovy adds a split() method to objects with a closure parameter. In the closure we must define a condition to split up the items in two lists. One list contains all the items that apply to the closure condition, the other list contains the rest of the items that don't apply to the closure condition.

def range = 1..10
def (even, odd) = range.split { it % 2 == 0 }
assert [2,4,6,8,10] == even
assert [1,3,5,7,9] == odd

def map = [language: 'Groovy', username: 'mrhaki', age: 36]
def (strings, others) = map.split { it.value instanceof String } 
assert 2 == strings.size()
assert 1 == others.size()
assert 'language' == strings[0].key && 'Groovy' == strings[0].value 
assert 'username' == strings[1].key && 'mrhaki' == strings[1].value 
assert 'age' == others[0].key && 36 == others[0].value