Find max value in arraylist

This example will show how to find the max value in an arraylist using groovy. The test years below represent the University of Wisconsin - Whitewater football championships. The first snippet will use groovy's max() method which extends DefaultGroovyMethods. The second snippet shows using java.util.Collections.max() which returns the maximum element of the given collection according to the natural ordering of its elements. The next snippet will display that max() is null aware which prevents you from having to filter nulls from the collection. Finally the last snippet shows how to pass a closure to determine the string with the longest length. A comparable example demonstrates how to get the largest value in arraylist in java using java 8, guava and apache commons.

Using max()

@Test
void locate_max_element() {

    def maximum = [2007, 2009, 2010, 2011, 2013]

    assert 2013, maximum.max()
}

Using jdk Collections.max

@Test
void locate_max_element_with_collections() {

    def maximumElements = [2007, 2009, 2010, 2011, 2013]

    assert 2013, Collections.max(maximumElements)
}

Max is null aware

@Test
void max_is_null_aware() {

    def elements = [2007, 2009, 2010, 2011, 2013, null]

    assert 2013, elements.max()
}

Find string with max length

@Test
void string_with_max_length () {

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

    assert "Bringing", elements.max { it.size() }
}