Get last element in list

This example will show how to find the last element in an ArrayList. While this may seem trivial, utilities exist to provide a more readable, eloquent approach vs the solution outlined in the straight up java section.

Straight up Java

This snippet will get the last element in a ArrayList using straight up java. It will check if the ArrayList is empty and if the size is greater than 0 returning the last element in the collection.

@Test
public void get_last_element_in_list_with_java () {

    List<String> strings = new ArrayList<String>();
    strings.add("one");
    strings.add("two");
    strings.add("three");

    String lastElement = null;
    if (!strings.isEmpty()) {
        lastElement = strings.get(strings.size() - 1);
    }

    assertEquals("three", lastElement);
}

Google Guava

Guava Iterables.getLast will return the last element in the iterable or the default value if the list is empty.

@Test
public void get_last_element_in_list_with_guava () {

    List<String> strings = Lists.newArrayList("one", "two", "three");

    String lastElement = Iterables.getLast(strings, null);

    assertEquals("three", lastElement);
}

Apache Commons

Apache commons CollectionUtils.get will return the element at the last index.

@Test
public void get_last_element_in_list_with_apachecommons () {

    List<String> strings = Lists.newArrayList("one", "two", "three");

    String lastElement = (String) CollectionUtils.get(strings, (strings.size() - 1));

    assertEquals("three", lastElement);
}