Find shortest length string in list

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

Setup

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

@Before
public void setUp() {
    randomStrings.add("George Washington");
    randomStrings.add("Zachary Taylor");
    randomStrings.add("Andrew Johnson");
    randomStrings.add("Warren G. Harding");
    randomStrings.add("Calvin Coolidge");
}

Straight up Java

In a traditional approach we will capture the first element in the list length setting it to a variable named shortest. Next we will loop over a list checking each element and comparing it to the shortest length. If the length is less than the previous we will set the shortest element to the current element. Finally in a junit assert we will validate that the smallest length string is Zachary Taylor.

@Test
public void shortest_string_java() {

    String shortest = randomStrings.get(0);

    for (String element : randomStrings) {
        if (element.length() < shortest.length()) {
            shortest = element;
        }
    }

    assertEquals("Zachary Taylor", shortest);
}

Java 8

Using 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 in reverse since we want the shortest first. Finally, calling the findFirst will return the first element wrapped in Optional.

@Test
public void longest_string_sort_java8() {

    Comparator<String> byLength = (e1, e2) -> e1.length() > e2.length() ? -1
            : 1;

    Optional<String> shortest = randomStrings.stream()
            .sorted(byLength.reversed()).findFirst();

    assertEquals("Zachary Taylor", shortest.get());
}

Google Guava

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

@Test
public void longest_string_guava() {

    Ordering<String> byLength = new Ordering<String>() {
        public int compare(String left, String right) {
            return Ints.compare(left.length(), right.length());
        }
    };

    Collections.sort(randomStrings, byLength);

    assertEquals("Zachary Taylor", Iterables.getFirst(randomStrings, ""));
}