Limit number of elements in arraylist

Using a random word generator we will show how to take the first number of elements from an arraylist. take() was introduced in Groovy 1.8.1 and can also be applied to iterable. In addition to take() a range of indices can be used to obtain a sublist. In a comparable example we demonstrate how to limit a specified number of elements from arraylist in java.

Limit using range

@Test
void using_range() {

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

    assert [1, 2, 3] == list[0..2]
}

Limit number of strings

@Test
void take_first_of_strings() {

    def stringList = ["overlax", "traducing",
                      "daemonian", "clarsach",
                      "raptus"]

    assert ["overlax", "traducing",
            "daemonian"] == stringList.take(3)
}

Limit number of integers

@Test
void limit_numbers_in_list() {

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

    assert [1, 2, 3] == list.take(3)
}