Skip to content

Groovy Guide — Collections: Lists, Maps, and Ranges

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Groovy Guide. We cover key concepts, practical examples, and best practices to help you master this topic.

Groovy collections use concise literal syntax with square brackets for lists and maps, plus rich methods for iteration, filtering, and transformation.

What You'll Learn

  • List literals and operations
  • Map literals and operations
  • Ranges and their uses
  • Spread operator
  • Collection GDK methods

Why It Matters

Groovy collections are the foundation of data manipulation. Their concise syntax and extensive methods make data processing expressive. Durga Antivirus Pro uses collections for scan results.

Real-World Use

Data processing pipelines, configuration objects, result aggregation, and API responses all use collections.

flowchart LR
    A["Collections"] --> B["Lists"]
    B --> C["Maps"]
    C --> D["Ranges"]
    D --> E["Methods"]
    A:::current --> B
    style A fill:#2563eb,stroke:#2563eb,color:#fff
    style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
    style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
    style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
    style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b

Lists

def list = [1, 2, 3, 4, 5]
def empty = []
def mixed = [1, "hello", true, 3.14]

// Indexing
list[0]    // 1
list[-1]   // 5 (last)
list[1..3] // [2, 3, 4] (range)

// Operators
list << 6                // Append
list += [7, 8]           // Add all
list -= [1, 2]           // Remove
list * 2                 // Repeat: [1,2,3,4,5,1,2,3,4,5]

Maps

def map = [name: "Alice", age: 30, active: true]
def empty = [:]

// Access
map.name      // "Alice"
map['age']    // 30
map.get('missing', 'default')

// Modification
map.city = "Portland"
map << [email: "a@example.com"]
map.remove('age')

// Iteration
map.each { key, value ->
    println "$key: $value"
}

Ranges

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

// Lists from ranges
(1..5).toList()  // [1, 2, 3, 4, 5]

// Iteration
(1..3).each { println it }

// Case statements
def grade(score) {
    switch(score) {
        case 90..100: return "A"
        case 80..<90: return "B"
        case 70..<80: return "C"
        default: return "F"
    }
}

// String ranges
('a'..'z').each { print it }

Spread Operator

def list1 = [1, 2, 3]
def list2 = [4, 5, 6]

// Spread list contents
def combined = [*list1, *list2]
// [1, 2, 3, 4, 5, 6]

// Spread map contents
def defaults = [host: "localhost", port: 8080]
def config = [*:defaults, debug: true]
// [host: "localhost", port: 8080, debug: true]

// Spread in method calls
def printThree(a, b, c) { "$a, $b, $c" }
printThree(*[1, 2, 3])  // "1, 2, 3"

Collection Methods

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

// Transformation
numbers.collect { it * 2 }      // [2, 4, 6, 8, 10]
numbers.findAll { it % 2 == 0 } // [2, 4]
numbers.grep { it > 3 }         // [4, 5]

// Aggregation
numbers.sum()      // 15
numbers.sum { it * it }  // 55
numbers.max()      // 5
numbers.min()      // 1

// Grouping
def people = [
    [name: "Alice", dept: "Eng"],
    [name: "Bob", dept: "Sales"],
]
people.groupBy { it.dept }

Common Mistakes

1. Empty map vs empty list

[:] is empty map, [] is empty list. They look similar but are different types.

2. Map property syntax with strings

map.'key' or map["key"] for string keys. map.key works for string keys that are valid identifiers.

3. List assignment semantics

list = list + [4] creates a new list. list << 4 modifies in place.

4. Range performance

(1..1000000) creates a large range object. Use for iteration, not storage.

5. Null-safe navigation

Use list?.collect { it } to avoid NPE on null collections.

Practice Questions

1. How do you create a list in Groovy? Use square brackets: [1, 2, 3]. Lists are java.util.ArrayList by default.

2. How do you access negative indices? list[-1] returns the last element. Negative indices count from the end.

3. What does the spread operator (*) do? It expands a collection into its individual elements, useful for combining collections or calling methods.

Challenge: Write a function that groups a list of maps by a given key using Groovy's collection methods.

FAQ

{{< faq question="Are Groovy lists Java-compatible?" >} Yes. Groovy lists implement java.util.List. They work seamlessly with Java code. {{< /faq >}}

{{< faq question="Can I use Java Streams with Groovy collections?" >} Yes. Groovy collections support Java streams via the .stream() method. {{< /faq >}}

{{< faq question="What is the default collection type?" >} Lists are ArrayList. Maps are LinkedHashMap (preserves insertion order). {{< /faq >}}

{{< faq question="How do I create type-specific collections?" >} Use as ArrayList, LinkedList, etc: [1, 2, 3] as LinkedList. {{< /faq >}}

{{< faq question="Are ranges memory-efficient?" >} Yes. Ranges store start, end, and step. They don't allocate all elements. Use for efficient iteration. {{< /faq >}}

Mini Project

Build a data analysis tool with Groovy collections:

def sales = [
    [product: "Widget", amount: 100, date: "2024-01-01"],
    [product: "Gadget", amount: 200, date: "2024-01-01"],
    [product: "Widget", amount: 150, date: "2024-01-02"],
    [product: "Gadget", amount: 50, date: "2024-01-02"],
]

def report = sales.groupBy { it.product }.collectEntries { product, transactions ->
    [product, [
        count: transactions.size(),
        total: transactions.sum { it.amount },
        avg: transactions.sum { it.amount } / transactions.size()
    ]]
}

println report
// [Widget: [count:2, total:250, avg:125], Gadget: [count:2, total:250, avg:125]]

What's Next

Now that you understand collections, explore control flow structures.

Topic Description Link
Groovy Control Flow If, switch, and loops {{< ref "07-control-flow" >}}
Groovy GPath Navigation syntax {{< ref "08-gpath" >}}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro