Groovy web console

subscribe to the feed Subscribe
to this
site

Thai'sTests

Published 3 weeks ago by DwS with tags groupBy
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
List people = [
    [lastName: "A", gender: 'f', age: 5],
    [lastName: "A", gender: 'f', age: 9],
    [lastName: "A", gender: 'm', age: 13],
    [lastName: "B", gender: 'm', age: 16],
    [lastName: "B", gender: 'm', age: 19],
    [lastName: "B", gender: 'f', age: 22],
    [lastName: "C", gender: 'm', age: 25],
    [lastName: "C", gender: 'm', age: 24],
]

println "// for each last name, print the oldest person: write in 1 command"
people.groupBy { it.lastName }.each { lastName, listByLastName -> println listByLastName.max { it.age } }

println()

println "// for each last name, print the oldest female person: write in 1 command"
people.findAll { it.gender=='f' }.groupBy { it.lastName }.each { lastName, listByLastName -> println listByLastName.max { it.age } }

println()

println "// for each last name, print lastName and the oldest female person: write in 1 command"
people.groupBy { it.lastName }.each { lastName, listByLastName -> println lastName+':'+listByLastName.findAll { it.gender=='f' }.max { it.age } }