Reading — step 1 of 5
Learn
~1 min readCollections and Closures
List literals look like Python:
def nums = [3, 1, 4, 1, 5, 9]
nums[0] // 3
nums.size() // 6
nums << 2 // append (mutates)
nums + [10, 20] // new list
nums.sort() // mutates and returns sorted
Map literals use colons (NOT =>):
def person = [name: "Ada", age: 36]
person.name // "Ada"
person["name"] // also works
person.role = "CEO" // add
person.each { k, v ->
println "$k: $v"
}
Map keys are strings by default. To use other types, quote with parens: [(1): "one"].
Groovy's collection API is rich:
nums.find { it > 3 } // first matching
nums.findAll { it > 3 } // all matching
nums.collect { it * 2 } // map
nums.sum() // 23
nums.unique() // distinct
it is the implicit single parameter inside a closure.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…