Groovy Tutorial: List Examples

by Didin J. on Feb 22, 2023 Groovy Tutorial: List Examples

More examples of Groovy lists such as list types, implementation, usages, and various operations that useful in the Groovy application

A list or sequence is an abstract data type that represents a finite number of ordered values, where the same value may occur more than once. An instance of a list is a computer representation of the mathematical concept of a tuple or finite sequence, the infinite analog of a list is a sequence of data elements made available over time. The Groovy list basically uses java.util.List as Groovy doesn’t define its own collection classes.

Table of Contents:

Before jumping to the example, make sure you have installed Java Virtual Machine and the Groovy SDK from Apache Groovy Official https://groovy.apache.org/download.html. Then set the groovy command to the environment variable. On Mac, we can use SDKMan to install the Groovy SDK.

sdk install groovy

Now, we can run our Groovy file using the groovy command after we put all Groovy codes in a file listGroovyExample.groovy.

groovy listGroovyExample.groovy

We are using Groovy Version: 4.0.9 and JVM: 17.0.4.1. There is some Groovy compiler online, but make sure their version is using the latest Groovy version to make this tutorial work.


Defining a List

In Groovy, we can define a List using this 'def' keyword with the right-side after equals using '[]'.

def list = [2, 1, 1, 2, 4]
def animals = ["Cat", "Cow", "Chicken"]

println list
println animals

Results:

[2, 1, 1, 2, 4]
[Cat, Cow, Chicken]

To define an empty list, we can do that like this.

def emptyList = []

println emptyList

Results:

[]


Types of List

The list can contain various data types such as Numbers, Strings, Objects, Nested Lists, and Heterogeneous lists. Also, we can specify the list as LinkedList instead of default java.utils.ArrayList.

List of numbers or integers example:

def nbr = [3, 4, 5, 6, 7]
println nbr

Results:

[3, 4, 5, 6, 7]

List of strings example:

def nbr = ["BMW", "TOYOTA", "CHEVROLET"]
println nbr

Results:

[BMW, TOYOTA, CHEVROLET]

List of Objects example:

class Car {

    String name
    String brand
    BigDecimal price

    Car(String name, String brand, BigDecimal price) {
        this.name = name
        this.brand = brand
        this.price = price
    }
}

def cars = [
    new Car('730i', 'BWM', 1500.0),
    new Car('TrailBlazer', 'Chevrolet', 1200.0),
    new Car('Fortuner', 'Toyota', 1100.0)
]

for (car in cars) {
    println "Name: $car.name, Brand: $car.brand, Price: $car.price"
}

Results:

Name: 730i, Brand: BWM, Price: 1500.0
Name: TrailBlazer, Brand: Chevrolet, Price: 1200.0
Name: Fortuner, Brand: Toyota, Price: 1100.0

Nested List example:

def nestedList = [['BWM', 'Mercedez Benz'], ['Ford', 'Chevrolet']]
def nestedList2 = [[1, 1, 1, [1, 1]], 2, [[2], 2]]

Results:

[[BWM, Mercedez Benz], [Ford, Chevrolet]]
[[1, 1, 1, [1, 1]], 2, [[2], 2]]

List of heterogeneous examples:

class Car {

    String name
    String brand
    BigDecimal price

    Car(String name, String brand, BigDecimal price) {
        this.name = name
        this.brand = brand
        this.price = price
    }
}

def hetList = ["John Doe", "US", 14000.0, new Car('730i', 'BWM', 1500.0)]

println hetList

Results:

[John Doe, US, 14000.0, Car@304b9f1a]

LinkedList example:

def linkedList = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet'] as LinkedList

println linkedList

Results:

[BWM, Mercedez Benz, Ford, Chevrolet]


Retrieve, Add, Remove, or Modify an Item from a List

We can retrieve, add, remove, or modify list items in the Groovy language. In the previous example, we always demonstrated to retrieve all items in a list. Now, we will show you to retrieve a single item using the "get" method. The item that will retrieve is based on the index of the list. The first index is 0.

Get an Item from a list example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']
String bmw = cars.getAt(0)
String volvo = cars.get(4)

println "$bmw and $volvo"

Results:

BWM and Volvo

Or we can use "[index]" to get a specific item from a list.

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']
String bmw = cars[0]
String volvo = cars[4]

println "$bmw and $volvo"

Results:

BWM and Volvo

Get the first and last item from the list example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']
String bmw = cars.first()
String honda = cars.last()
String head = cars.head()

println "$head, $bmw and $honda"

Results:

BWM, BWM and Honda

Get all items from a list excluding the last item example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

println cars.init()

Results:

[BWM, Mercedez Benz, Ford, Chevrolet, Volvo]

Get all items from a list excluding the first item example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

println cars.tail()

Results:

[Mercedez Benz, Ford, Chevrolet, Volvo, Honda]

Get the first items from a list:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

println cars.take(3)

Results:

[BWM, Mercedez Benz, Ford]

Get the last items from a list:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

println cars.takeRight(3)

Results:

[Chevrolet, Volvo, Honda]

To add items to a list, simply by using the "add" method.

Add items to the last of a list example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet']
cars.add("Volvo")
cars.add("Honda")

println cars

Results:

[BWM, Mercedez Benz, Ford, Chevrolet, Volvo, Honda]

Add an item to the specific index of a list example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet']
cars.putAt(2, 'Honda')

println cars

Results:

[BWM, Mercedez Benz, Honda, Chevrolet]

Remove an item from a list at a specific index example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']
cars.removeAt(0)

println cars

Results:

[Mercedez Benz, Ford, Chevrolet, Volvo, Honda]

Remove the last item from a list example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']
cars.removeLast()

println cars

Results:

[BWM, Mercedez Benz, Ford, Chevrolet, Volvo]

Remove some items by numbers of items starting from the head example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

println cars.drop(3)

Results:

[Chevrolet, Volvo, Honda]

Remove some items by numbers of items starting from the tail example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

println cars.dropRight(3)

Results:

[BWM, Mercedez Benz, Ford]


Copy or Merge Lists Example

Basically, copying or duplicating a list simply just creates another list variable with the value of the list that will be copied.

Copy list example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']
def cars2 = cars

println cars2

Results:

[BWM, Mercedez Benz, Ford, Chevrolet, Volvo, Honda]

Merge lists using the "addAll" example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']
def motorcycles = ['Ducati', 'Yamaha', 'Suzuki']

cars.addAll(motorcycles)

println cars

Results:

[BWM, Mercedez Benz, Ford, Chevrolet, Volvo, Honda, Ducati, Yamaha, Suzuki]

Merge or combine lists using a plus example:

def employees = ['John Doe', 'Jane Doe', 'Frank Doedoel']
def salaries = [2000.0, 2500.0, 3000.0]

def newlist = employees + salaries

println newlist

Results:

[John Doe, Jane Doe, Frank Doedoel, 2000.0, 2500.0, 3000.0]


Iterate a List Example

There are built-in methods to iterate over a list. We can do that using the "each", "eachWithIndex" method, or "for" loop.

Iterate using "each" method example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

cars.each { car ->
    println car
}

Results:

BWM
Mercedez Benz
Ford
Chevrolet
Volvo
Honda

Iterate using the "eachWithIndex" example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

cars.eachWithIndex { car, idx ->
    println idx + 1 + ": " + car
}

Results:

1: BWM
2: Mercedez Benz
3: Ford
4: Chevrolet
5: Volvo
6: Honda

Iterate using the "for" loop example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

for (car in cars) {
    println car
}

Results:

BWM
Mercedez Benz
Ford
Chevrolet
Volvo
Honda


List Filter Examples

Basic list filter example:

def nbrs = [2, 3, 4, 5, 6, 8, 9, 9, 3, 4, 5, 3, 3]

println nbrs.findAll { it == 3 }

Results:

[3, 3, 3, 3]

Filter a list by field name example:

class Car {

    String name
    String brand
    BigDecimal price

    Car(String name, String brand, BigDecimal price) {
        this.name = name
        this.brand = brand
        this.price = price
    }
}

def cars = [
    new Car('730i', 'BMW', 1500.0),
    new Car('TrailBlazer', 'Chevrolet', 1200.0),
    new Car('520i', 'BMW', 1440.0),
    new Car('320i', 'BMW', 1300.0),
    new Car('Fortuner', 'Toyota', 1100.0)
]

def allBmw = cars.findAll { car -> car.brand.equals('BMW') }

allBmw.each { a ->
    println "Model: $a.name, Brand: $a.brand, Price: $a.price"
}

Results:

Model: 730i, Brand: BMW, Price: 1500.0
Model: 520i, Brand: BMW, Price: 1440.0
Model: 320i, Brand: BMW, Price: 1300.0


Sort a List Example

Simple sort a list example:

def nbrs = [2, 3, 4, 5, 6, 8, 11, 9, 21, 4, 5, 1, 23]

println nbrs.sort()

Results:

[1, 2, 3, 4, 4, 5, 5, 6, 8, 9, 11, 21, 23]

Sort with closure example:

def cars = ['BWM', 'Mercedez Benz', 'Ford', 'Chevrolet','Volvo', 'Honda']

println cars.sort { it.length() }
println cars.sort { a, b -> a.length() <=> b.length() }
println cars.sort { a, b -> b.length() <=> a.length() }

Results:

[BWM, Ford, Volvo, Honda, Chevrolet, Mercedez Benz]
[BWM, Ford, Volvo, Honda, Chevrolet, Mercedez Benz]
[Mercedez Benz, Chevrolet, Volvo, Honda, Ford, BWM]

Actually, there are a lot of methods that might be useful for your Groovy application. But for now, we just show you some of the most commonly used by the most applications.  You can split, reverse order, remove duplicates, and more. Check this Groovy list doc.

That it's, the Groovy list examples. You can find the example source codes on GitHub.

That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:

Thanks!

Loading…