Fundamentals 5 min read

Master Groovy List Operations: From Java to Powerful Scripting

This tutorial shows how to convert a Java class that filters names into concise Groovy scripts, demonstrates Groovy list literals, index access, and built‑in collection methods like each, any, every, find, and findAll, providing complete code examples.

FunTester
FunTester
FunTester
Master Groovy List Operations: From Java to Powerful Scripting

In the previous article the author showed how Java code can be transformed into Groovy. This follow‑up demonstrates Groovy’s native support for list operations.

First, a Java class that filters a list of names longer than three characters is presented. The class contains a filter method and a main method that builds an ArrayList, adds four names, calls filter, and prints the results.

package com.fun;

import com.fun.frame.httpclient.FanLibrary;
import org.slf4j.Logger;

class TSSS extends FanLibrary {
    public static Logger logger = getLogger(TSSS.class);

    public static void main(String[] args) {
        List names = new ArrayList();
        names.add("Ted");
        names.add("Fred");
        names.add("Jed");
        names.add("Ned");
        List shortNames = filter(names, 3);
        output(shortNames.size());
        for (Iterator i = shortNames.iterator(); i.hasNext();) {
            String s = (String) i.next();
            output(s);
        }
    }

    public static List filter(List strings, int length) {
        List result = new ArrayList();
        for (String str : strings) {
            if (str.length() < length + 1) {
                result.add(str);
            }
        }
        return result;
    }
}

Using Arrays.asList() the same logic can be written more concisely in Java, but the article then rewrites the program as a Groovy script, dropping the class and static typing.

List names = new ArrayList()
names.add("Ted")
names.add("Fred")
names.add("Jed")
names.add("Ned")
List shortNames = filter(names, 3)
println shortNames.size()
for (String s : shortNames) {
    println s
}

def filter(List strings, int length) {
    List result = new ArrayList()
    for (String str : strings) {
        if (str.length() < length + 1) {
            result.add(str)
        }
    }
    return result
}

Groovy further simplifies list handling with literal syntax. A list can be created with def names = [] or populated directly: def names = ["Ted", "Fred", "Jed", "Ned"]. Elements are accessed and modified via the index operator, e.g., assert names[1] == "Fred" and names[1] = "Frederic".

Groovy also decorates core JDK collections with convenient methods such as each() for iteration, findAll() for filtering, and predicates like any and every. Example usage:

println names.any { it.length() > 3 }
println names.every { it.length() > 3 }
println names.find { it.length() > 3 }
println names.findAll { it.length() > 2 }
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaprogrammingCode ExampleScriptingListGroovy
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.