Chuyển đến nội dung

Bài 15 · Collections and Closures

Collection Methods in Depth

Master the Groovy GDK collection methods: each, collect, find, findAll, inject, any, every, groupBy, sum, min, max, sort, take, drop, partition and lazy chains, with a pipeline example.

Groovy's closures and collections meet in a family of methods that replace almost every loop you would write in Java. They are short, expressive and read like a description of what you want, not how to get it. Once you know about ten of them, you can write data-processing code in a few lines.

This lesson tours the methods you will use daily, shows how to chain them, and finishes with a worked pipeline. Groovy is read-only on this site; each section is paired with a Java stream stand-in you can run to see the same results.

The transformation family

each

Runs a closure for every element and returns the original collection. Use it for side effects such as printing.

GROOVY
['a', 'b'].each { println it }

collect: transform every element

GROOVY
println [1, 2, 3].collect { it * it }             // [1, 4, 9]
println ['ada', 'bob'].collect { it.capitalize() }   // [Ada, Bob]
println [1, 2, 3]*.plus(10)                         // [11, 12, 13] same idea with spread

collect always returns a list with the same size as the input. To transform AND flatten use collectMany:

GROOVY
println [[1, 2], [3]].collectMany { it }            // [1, 2, 3]
println ['ab', 'cd'].collectMany { it.toList() }    // [a, b, c, d]

findAll and grep: keep the matching elements

GROOVY
println((1..10).findAll { it % 3 == 0 })      // [3, 6, 9]
println ['apple', 'kiwi', 'fig'].findAll { it.size() > 3 }   // [apple, kiwi]
println ['a', 1, 'b', 2].grep(Integer)         // [1, 2]      grep accepts a classifier
println ['x1', 'y2', 'x3'].grep(~/x.*/)        // [x1, x3]

grep uses the same matching as switch (isCase), so it takes classes, ranges, patterns and closures. findAll with no closure returns the truthy elements.

find, findIndexOf: locate one element

GROOVY
println [4, 9, 12].find { it > 5 }                // 9   first match, or null
println [4, 9, 12].findIndexOf { it > 5 }         // 1
println [4, 9, 12].findLastIndexOf { it > 5 }     // 2
println [4, 9, 12].find { it > 50 }               // null

any, every, count

GROOVY
println [1, 2, 3].any { it > 2 }       // true
println [1, 2, 3].every { it > 0 }     // true
println [1, 2, 3].count { it > 1 }     // 2

any and find stop at the first match, which makes them the right tool for breaking out of a loop early.

Reducing: inject, sum, min and max

inject folds a collection into a single value, starting from a seed:

GROOVY
println [1, 2, 3, 4].inject(0) { acc, n -> acc + n }              // 10
println [1, 2, 3, 4].inject(1) { acc, n -> acc * n }              // 24
println ['a', 'b', 'c'].inject('') { acc, s -> acc + s.toUpperCase() }   // ABC

Without a seed the first element is the start value. For common cases use dedicated methods:

GROOVY
def people = [[name: 'Ada', age: 36], [name: 'Bob', age: 30], [name: 'Cy', age: 51]]
println people.sum { it.age }                   // 117
println people.max { it.age }.name              // Cy
println people.min { it.age }.name              // Bob
println people*.age.max()                       // 51
println people.sum { it.age } / people.size()   // 39
Java Java stand-in: map, filter and reduce with streams

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Grouping and partitioning

GROOVY
def words = ['kiwi', 'apple', 'fig', 'banana', 'plum']

println words.groupBy { it.size() }
// [4:[kiwi, plum], 5:[apple], 3:[fig], 6:[banana]]

println words.countBy { it.size() > 4 }
// [false:3, true:2]

println words.split { it.size() > 4 }
// [[apple, banana], [kiwi, fig, plum]]    first list = matching elements

groupBy returns a map from a key to the list of members; countBy counts instead; split separates matching from non-matching elements into two lists.

Slicing and ordering

GROOVY
def xs = [5, 3, 8, 1, 9, 2]
println xs.take(3)                 // [5, 3, 8]
println xs.drop(3)                 // [1, 9, 2]
println xs.takeWhile { it > 2 }    // [5, 3, 8]
println xs.dropWhile { it > 2 }    // [1, 9, 2]
println xs.sort(false).reverse().take(2)   // [9, 8]  (top two)
println xs.min()                           // 1
println xs.toSorted()                      // [1, 2, 3, 5, 8, 9]  Groovy 2.4+ copy
println xs.toUnique()                      // copy without duplicates
println xs.indices                         // 0..5
println xs.collate(2)                      // [[5, 3], [8, 1], [9, 2]]
println xs.withIndex().collect { v, i -> "$i=$v" }

toSorted and toUnique return copies and never modify the original, which makes them safer than sort() and unique().

Several collections at once

GROOVY
def names = ['Ada', 'Bob']
def ages = [36, 30]
println [names, ages].transpose()                  // [[Ada, 36], [Bob, 30]]
println [names, ages].transpose().collectEntries { n, a -> [(n): a] }   // [Ada:36, Bob:30]
println names.indexed()                             // [0:Ada, 1:Bob]
println(([1, 2, 3] + [4]).subsequences().size())   // 15 non-empty sub-lists

combinations() on a list of lists yields the cartesian product: [[1, 2], ['a', 'b']].combinations() gives [[1, a], [2, a], [1, b], [2, b]].

Lazy versus eager

Every method above creates intermediate lists. For big data, an Iterator or Java Streams avoids that; Groovy collections work with streams too: list.stream().filter { it > 2 }.map { it * 2 }.toList(). Groovy adds closure support for Java functional interfaces, so lambdas and closures mix freely. For most scripts the plain GDK methods are fast enough, and much shorter.

A worked pipeline

Let us total the revenue of paid orders by customer and list the top two.

GROOVY
def orders = [
    [customer: 'Ada',  amount: 120.50, paid: true],
    [customer: 'Bob',  amount: 80.00,  paid: false],
    [customer: 'Ada',  amount: 30.00,  paid: true],
    [customer: 'Cy',   amount: 200.00, paid: true],
    [customer: 'Bob',  amount: 45.25,  paid: true]
]

def totals = orders
    .findAll { it.paid }
    .groupBy { it.customer }
    .collectEntries { name, list -> [(name): list.sum { it.amount }] }

def top = totals.sort { -it.value }.take(2)
println top

Reading the chain from top to bottom tells the story: keep paid orders, group by customer, sum each group, sort by total descending, take two. The result is [Cy:200.00, Ada:150.50]. The Java version below does the same.

Java Java stand-in: the paid-orders pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Using each to build a result list. Use collect or findAll instead.
  • Forgetting that sort() and unique() mutate; prefer toSorted() and toUnique().
  • Expecting return in each to stop the loop. Use find, any or takeWhile.
  • Calling sum() on an empty list and getting null; give a seed: sum(0).

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which method transforms every element of a list into a new list?

    collect maps each element through the closure and returns the results as a list.
  2. 2. What does [1, 2, 3, 4].inject(0) { acc, n -> acc + n } return?

    inject folds the list starting from 0: 0+1+2+3+4 = 10.
  3. 3. Which is the best way to stop looking after the first matching element?

    find and any stop at the first match. break is not allowed inside a closure.
  4. 4. What does words.groupBy { it.size() } return?

    groupBy builds a map whose keys come from the closure and whose values are lists of members.
  5. 5. Which method returns a sorted COPY and never modifies the original list?

    toSorted() is the non-mutating counterpart of sort().

Summary

  • collect transforms, findAll and grep filter, find and any stop early, inject folds.
  • sum, min, max accept closures; groupBy, countBy and split group.
  • take, drop, takeWhile, dropWhile, collate and toSorted slice and order safely.
  • Chain methods to describe a pipeline instead of writing loops with temporary variables.

Next: Classes and Properties

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.