Find longest length string in list

This example will show how get the maximum length string in an arraylist using java, java 8 and guava. In the set up we will initialize an arraylist of random strings. In a comparable example we demonstrate how to find the maximum length string in a collection using groovy.


List<String> randomStrings = new ArrayList<>();

public void setUp() {

Straight up Java

In a traditional approach we will capture the first element in the list length setting it to a variable named longestString. Next we will iterate over a list checking each element and comparing it to the longestString length. If the length is greater than the previous we will set the longestString element to the current element. Finally in a junit assert we will validate that the longest length is equal to "ttnBGouocZ".

public void longest_string_java() {

    String longestString = randomStrings.get(0);
    for (String element : randomStrings) {
        if (element.length() > longestString.length()) {
            longestString = element;
    assertEquals("ttnBGouocZ", longestString);

Java 8

Using a java 8 lambda expression, we will create a java Comparator that will check the length of string which would make the list ascending. Converting a list to a stream calling sorted we will pass the comparator which will return the longest string first. Finally, calling the findFirst will return the first element wrapped in Optional.

public void longest_string_sort_java8() {

    Optional<String> longest =
            .sorted((e1, e2) -> e1.length() > e2.length() ? -1 : 1)

    assertEquals("ttnBGouocZ", longest.get());

Google Guava

Using guava fluent ordering class we will compare the length of the strings and pass the ordering object to Collections.sort reversing the order of the comparator. In our assert we will use the Iterables.getFirst to retrieve the first element in the list.

public void longest_string_guava() {

    Ordering<String> byLength = new Ordering<String>() {
        public int compare(String left, String right) {
            return, right.length());
    Collections.sort(randomStrings, byLength.reverse());

    assertEquals("ttnBGouocZ", Iterables.getFirst(randomStrings, ""));