Filter list by class field

This example will show how to filter a list of objects by field in a class using groovy. The set is a class Currency and we will initialize a collection creating three elements. Next calling the findAll() method we will pass a closure that filter the list by checking if the amount is greater than 1.03. The result is 2 elements. The second snippet will demonstrate how to reduce the list and only return even numbers. A related example of show how to filter elements in a list using java 8.

Setup

@ToString
class Currency {
    def amount
    def year
    def country
}

Filter list by field

@Test
void filter_object_by_field () {

    def currencyCollection = [new Currency(amount: 1.04, year: 1998, country: "US"),
                  new Currency(amount: 1.02, year: 2001, country: "US"),
                  new Currency(amount: 1.07, year: 2005, country: "EU")]

    def filteredList = currencyCollection.findAll({p -> p.amount > 1.03})

    print(filteredList)

    assert 2 == filteredList.size()
}

Output

[com.levelup.groovy.collections.FilterCollection$Currency(1.04, 1998, US), com.levelup.groovy.collections.FilterCollection$Currency(1.07, 2005, EU)]

Filter even numbers

@Test
void filter_even_numbers() {

    def numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

    def evenNumbers = numbers.findAll({ it % 2 == 0 })

    assert [2, 4, 6, 8] == evenNumbers
}