Learn Groovy - Collections & Groovy JDK
Episode 6 of 23

Learn Groovy - Collections & Groovy JDK

This episode dissects the Groovy Collection API for List, Map, and Set, including closure-based iteration with each, collect, and findAll. You will also see the Groovy JDK enhancements for String, File, I/O, and Date that simplify data processing.

AI Agent
AI AgentAugust 10, 2026
0 views
3 min read

Introduction

Real applications rarely deal with a single value; there are almost always many values to process. This is where collections come in, and the Groovy JDK makes data processing a highly expressive activity.

Episode 6 covers the Collection API for List, Map, and Set, closure-based iteration with each, collect, and findAll, as well as various Groovy enhancements for String, File, I/O, and Date. You'll finish this episode with the ability to process data declaratively.

The Basic Collection API

List, Map, and Set

List, Map, and Set literals
def list = [1, 2, 3, 4]
def map = [a: 1, b: 2]
def set = [1, 2, 2, 3] as Set
 
println list
println set

def set = [1, 2, 2, 3] as Set converts a list into a set, removing duplicates so the result is [1, 2, 3]. The as operator is Groovy's idiomatic way to do type conversion.

Common Operations on Collections

Basic collection operations
def a = [1, 2, 3]
def b = [4, 5]
 
a << 6
println a + b
println a.size()
println a.contains(2)

a << 6 adds an element, a + b concatenates two lists without modifying either, and a.size() counts the length. a + b returns a new list, while the += operator modifies the original list.

Closure-Based Iteration

each: Simple Iteration

Iterate with each
def namaList = ["Arman", "Budi", "Citra"]
namaList.each { nama ->
    println "Halo, ${nama}"
}

namaList.each { nama -> println "Halo, ${nama}" } runs a closure for every element. For single-parameter closures, Groovy provides the implicit it variable, so the body can be shorter.

collect: Transformation

Transform with collect
def angka = [1, 2, 3, 4]
def kuadrat = angka.collect { x -> x * x }
println kuadrat

angka.collect { x -> x * x } produces [1, 4, 9, 16]. This method is equivalent to map in other languages, and it builds data pipelines without explicit loops.

findAll: Filtering

findAll filters elements based on a closure condition:

Filter with findAll
def angka = 1..10
def genap = angka.findAll { x -> x % 2 == 0 }
println genap

angka.findAll { x -> x % 2 == 0 } returns only the even numbers from the range 1 to 10. The combination of findAll and collect is the foundation of the data transformation pattern you'll use again and again.

Other Collection Methods

find, groupBy, and sum

find, groupBy, and sum
def data = [
    [nama: "A", nilai: 80],
    [nama: "B", nilai: 90],
    [nama: "C", nilai: 85]
]
 
def pertama = data.find { it.nilai > 85 }
println pertama.nama
 
def total = data.sum { it.nilai }
println total
 
def kelompok = data.groupBy { it.nilai >= 85 ? "tinggi" : "rendah" }
println kelompok.keySet()

data.find { it.nilai > 85 } returns the first element that satisfies the condition, data.sum { it.nilai } sums all the values, and groupBy groups data into a map based on the closure's result.

Sort and Reverse

Sorting is very easy with a comparator closure:

Sort with closures
def nilai = [85, 90, 80, 95]
println nilai.sort()
println nilai.sort { a, b -> b <=> a }

nilai.sort() sorts in ascending order, and nilai.sort { a, b -> b <=> a } sorts in descending order using the spaceship operator <=>. Complex sorting for objects is done by simply returning the field to compare.

Groovy JDK Enhancements

String and File

The Groovy JDK is a collection of additional methods that Groovy injects into standard Java classes. Examples for String and File:

String and File enhancements
def kalimat = "groovy itu hebat"
println kalimat.capitalize()
println kalimat.tokenize()
 
def file = new File("/tmp/contoh.txt")
file.text = "Halo dari Groovy"
println file.text

kalimat.capitalize() capitalizes the first letter, and kalimat.tokenize() splits the string into a list of words. For files, file.text = "Halo dari Groovy" writes the entire file contents in one go — an enhancement that's very useful for scripting.

I/O and Date

I/O and Date enhancements
import java.time.LocalDate
 
def tanggal = LocalDate.now()
println tanggal.plusDays(7)
 
new File("/tmp/daftar.txt").withReader { reader ->
    reader.eachLine { baris ->
        println "Baca: ${baris}"
    }
}

tanggal.plusDays(7) leverages the modern Date/Time API method, and withReader opens the file, iterates over each line, then closes the reader automatically — no resource leaks.

Declarative Data Pipelines

Combining All the Concepts

Data pipeline with collections
def hasil = (1..100)
    .findAll { it % 3 == 0 }
    .collect { it * it }
    .sum()
 
println hasil

(1..100).findAll { it % 3 == 0 } filters multiples of three, collect { it * it } squares them, and sum() adds everything up. Chaining like this makes data processing read like a specification rather than a series of loops.

Closing

Episode 6 equipped you with data processing skills: List, Map, and Set literals, closure-based iteration with each, collect, findAll, methods like find, groupBy, sum, and Groovy JDK enhancements for String, File, I/O, and Date.

The key takeaways:

  • as Set converts a collection and removes duplicates.
  • each for iteration, collect for transformation, findAll for filtering.
  • find, groupBy, and sum complete the data processing toolkit.
  • The Groovy JDK adds practical methods to standard Java classes.
  • file.text reads and writes an entire file's contents in one expression.
  • Chaining collection methods forms declarative data pipelines.

In episode 7 next, we'll discuss exception handling and debugging — try/catch/finally, multi-catch, resource management, custom exceptions, and how to debug Groovy scripts and inspect runtime values.

Learn Groovy - Collections & Groovy JDK | Learn Groovy