Tutorial by Examples

Lists def lst = ['foo', 'bar', 'baz'] // using implicit argument lst.each { println it } // using explicit argument lst.each { val -> println val } // both print: // foo // bar // baz Iterate with index def lst = ['foo', 'bar', 'baz'] // explicit arguments are required lst.each...
def lst = ['foo', 'bar', 'baz'] lst.collect { it } // ['foo', 'bar', 'baz'] lst.collect { it.toUpperCase() } // ['FOO', 'BAR', 'BAZ'] To collect keys or values from a maps def map = [foo: 'FOO', bar: 'BAR', baz: 'BAZ'] def keys = map.collect { it.key } // ['foo', 'bar', 'baz'] def vals = m...
def lst = [10, 20, 30, 40] lst.findAll { it > 25 } // [30, 40]
def lst = [10, 20, 30, 40] lst.find { it > 25 } // 30. Note: it returns a single value
From lists def lst = ['foo', 'bar', 'baz'] // for each entry return a list containing [key, value] lst.collectEntries { [it, it.toUpperCase()] } // [foo: FOO, bar: BAR, baz: BAZ] // another option, return a map containing the single entry lst.collectEntries { [(it): it.toUpperCase()] } // [...
Apply the transformation to non-collection entries, delving into nested collections too and preserving the whole structure. def lst = ['foo', 'bar', ['inner_foo', 'inner_bar']] lst.collectNested { it.toUpperCase() } // [FOO, BAR, [INNER_FOO, INNER_BAR]]
def lst = ['foo', 'bar', ['inner_foo', 'inner_bar']] lst.flatten() ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​...
def lst = ['foo', 'foo', 'bar', 'baz'] // *modifies* the list removing duplicate items lst.unique() // [foo, bar, baz] // setting to false the "mutate" argument returns a new list, leaving the original intact lst.unique(false) // [foo, bar, baz] // convert the list to a Set, thu...
nrs = [1, 2, 3, 4, 5, 6, 7, 8, 9] lets = ['a', 'b', 'c', 'd', 'e', 'f'] println GroovyCollections.transpose([nrs, lets]) .collect {le -> [(le[0]):le[1]]}.collectEntries { it } or println [nrs,lets].transpose().collectEntries{[it[0],it[1]]} // [1:a, 2:b, 3:c, 4:d, 5:e, 6:f...

Page 1 of 1