Groovy, lesson 7
Real programs juggle many values at once: every price on a receipt, every vote in an election.
Groovy builds its collections on Java's List and Map, but gives them a literal syntax and a
large set of helpful methods.
A list literal is written in square brackets:
Groovy lists are ordinary, changeable Java ArrayLists. << adds an element at the end, and
scores[1] = 8 replaces one.
Instead of writing a loop for every task, pass a closure to one of the collection methods:
collect builds a new list from the closure's results, findAll keeps the elements for which the
closure is true, and find returns the first match (or ). returns a sorted
copy; plain sorts the list itself.
2 exercises to try what you just read.
nullsort(false)sort()inject combines all elements into one value, starting from an initial value:
These methods return new values, so you can chain them:
prices.findAll { it > 3 }.collect { it * 2 }.sum() gives 44.
A map stores key → value pairs. Its literal uses key: value inside brackets:
[:] is an empty map. Groovy maps keep their entries in the order you inserted them.
Loop over a map with each, taking the key and value as two closure parameters:
sort() on a map returns a new map ordered by key, which is perfect for tidy output.
Counting how often each item appears is so common that Groovy has countBy. The closure says
what to count by; for the items themselves, use { it }:
Read one line of whole numbers separated by spaces (there is at least one). Print how many there are, their total and the largest one.
Sample input:
Sample output:
Each line of input is one vote: the name of a candidate. Count the votes and print each candidate with their number of votes, in alphabetical order, one per line.
Sample input:
Sample output:
def scores = [12, 7, 30]
def names = ["Ana", "Bo"]
def empty = []
println scores[0] // 12 (positions start at 0)
println scores[-1] // 30 (negative positions count from the end)
println scores.size() // 3
scores << 99 // append: [12, 7, 30, 99]
println scores.contains(7) // truedef prices = [4, 10, 3, 8]
prices.each { println it } // visit every element
def doubled = prices.collect { it * 2 } // [8, 20, 6, 16]
def cheap = prices.findAll { it < 5 } // [4, 3]
def firstBig = prices.find { it > 5 } // 10
println prices.sum() // 25
println prices.max() // 10
println prices.sort(false) // [3, 4, 8, 10]
println prices.any { it > 9 } // truedef total = prices.inject(0) { sum, p -> sum + p } // 25def stock = [apples: 12, pears: 4] // keys are the strings "apples" and "pears"
println stock["apples"] // 12
println stock.pears // 4 (dot syntax works for simple keys)
stock["plums"] = 9 // add or replace an entry
println stock.get("kiwis", 0) // 0, and stores kiwis: 0 as a default
println stock.containsKey("apples") // truestock.each { fruit, n -> println "${fruit}: ${n}" }println(["red", "blue", "red"].countBy { it }) // [red:2, blue:1]12 7 30 1Count: 4
Total: 50
Max: 30Mila
Theo
Mila
AvaAva 1
Mila 2
Theo 1