CodeToLive

Groovy Collections & Closures

Groovy enhances Java's collection framework with more concise syntax and powerful methods, and introduces closures for functional programming.

Collections in Groovy

Groovy provides native syntax for lists, maps, and ranges:

Lists

def numbers = [1, 2, 3, 4, 5]  // ArrayList by default
def linkedList = [1, 2, 3] as LinkedList

// Common operations
numbers << 6            // Add element
numbers[0]              // Get first element (1)
numbers[-1]             // Get last element (6)
numbers[1..3]           // Sublist [2, 3, 4]

Maps

def person = [name: 'Alice', age: 25]  // LinkedHashMap by default

// Access properties
person.name             // 'Alice'
person['age']           // 25
person.city = 'Boston'  // Add new entry

Ranges

def range = 1..10        // Inclusive range
def exclusive = 1..<10  // Exclusive range

// Useful for iterations
(5..1).each { println it }  // Countdown

Closures

Closures are blocks of code that can be assigned to variables and passed as parameters:

// Basic closure
def greet = { name -> "Hello, $name!" }
println greet('Alice')  // "Hello, Alice!"

// Closure with implicit parameter (it)
def square = { it * it }
println square(4)       // 16

Collection Methods with Closures

Groovy adds many useful methods to collections that accept closures:

def numbers = [1, 2, 3, 4, 5]

// Iteration
numbers.each { println it }

// Filtering
def evens = numbers.findAll { it % 2 == 0 }

// Transformation
def squares = numbers.collect { it * it }

// Sorting
def sorted = numbers.sort { a, b -> b <=> a }

Advanced Collection Features

  • Spread operator (*.): Invoke method on all elements
  • Grouping: groupBy() to create maps of lists
  • Injection: inject() for fold/reduce operations
  • Flattening: flatten() nested collections
← Back to Tutorials