Search

Dark theme | Light theme

January 16, 2010

Groovy Goodness: Apply Method to All Elements in a List

In Groovy we have several ways to achieve the same thing. For example we can apply a method to all elements in a list with the collect() method or with *..

class User { 
    String name 
    String aloud() { name.toUpperCase() }
    String toString() { name }
}

def users = [new User(name: 'mrhaki'), new User(name: 'hubert')]

assert ['mrhaki', 'hubert'] == users*.toString()
assert ['MRHAKI', 'HUBERT'] == users*.aloud()
assert ['mrhaki', 'hubert'] == users.collect { it.toString() }
assert ['MRHAKI', 'HUBERT'] == users.collect { it.aloud() }