// collection_methods.groovy — each, collect, findAll, find, inject, groupBy and friends. def orders = [ [id: 'PO-1', customer: 'Acme', total: 250, status: 'SHIPPED'], [id: 'PO-2', customer: 'Globex', total: 90, status: 'NEW'], [id: 'PO-3', customer: 'Acme', total: 1200, status: 'NEW'], [id: 'PO-4', customer: 'Initech', total: 40, status: 'CANCELLED'], ] orders.each { println "${it.id}: ${it.total}" } // do something with each orders.eachWithIndex { o, i -> println "$i -> ${o.id}" } println orders.collect { it.id } // transform: [PO-1, PO-2, PO-3, PO-4] println orders*.customer.unique() // spread + unique: [Acme, Globex, Initech] println orders.findAll { it.status == 'NEW' }*.id // filter: [PO-2, PO-3] println orders.find { it.total > 1000 }?.id // first match: PO-3 println orders.any { it.status == 'CANCELLED' } // true println orders.every { it.total > 0 } // true println orders.count { it.customer == 'Acme' } // 2 println orders.sum { it.total } // 1580 println orders.max { it.total }.id // PO-3 println orders.sort(false) { -it.total }*.id // sorted copy, biggest first // inject: fold everything into one value (like reduce) def total = orders.inject(0) { acc, o -> acc + o.total } println "Total: $total" // groupBy and countBy def byCustomer = orders.groupBy { it.customer } println byCustomer.collectEntries { k, v -> [k, v*.total.sum()] } // [Acme:1450, Globex:90, Initech:40] println orders.countBy { it.status } // [SHIPPED:1, NEW:2, CANCELLED:1] // collectEntries: build a map println orders.collectEntries { [it.id, it.status] } // split: two lists in one pass def (big, small) = orders.split { it.total >= 100 } println "big=${big*.id} small=${small*.id}" // collate: chunk into batches (great for APIs with batch limits) println((1..7).collate(3)) // [[1, 2, 3], [4, 5, 6], [7]] // flatten and collectMany println([[1, 2], [3, [4]]].flatten()) // [1, 2, 3, 4] def lines = [[sku: 'AX', qty: 2], [sku: 'BX', qty: 1]] println lines.collectMany { l -> [l.sku] * l.qty } // [AX, AX, BX]