Find min value in arraylist

This example will show how to find the smallest value in an arraylist using groovy. The years below represent loosing season by Wisconsin Badgers football team. The first snippet will use groovy's min() method which will return the smallest integer. The second snippet shows using java.util.Collections.min() which returns the minimum element of the given collection according to the natural ordering of its elements. The next snippet will display that min() is null aware which prevents the need to remove null elements from a collection. Finally, the last snippet shows how to pass a closure to determine a collection of strings with the smallest length. A comparable example demonstrates how to get the smallest value in arraylist in java using java 8, guava and apache commons.

Using min()

@Test
void locate_min_element() {

    def minimum = [2001, 1995, 1992, 1991, 1990]

    assert 1990, minimum.min()
}

Using jdk Collections.min

@Test
void locate_min_element_with_collections() {

    def minimumElements = [2001, 1995, 1992, 1991, 1990]

    assert 1990, Collections.min(minimumElements)
}

Min is null aware

@Test
void min_is_null_aware() {

    def elements = [2001, 1995, 1992, 1991, 1990, null]

    assert 1990, elements.min()
}

Find string with min length

@Test
void string_with_min_length () {

    def elements = ["Bringing", "Home", "The", "Bacon"]

    assert "The", elements.min { it.size() }
}