Get first element in list

This example will show how to get the first element in a collection. 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 first element in a collection using java. It will check if the ArrayList is empty and if the size is greater than 0. It then will return the first element by getting the first element in the list.

@Test
public void get_first_element_in_list_with_java () {

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

    String firstElement = null;
    if (!strings.isEmpty() && strings.size() > 0) {
        firstElement = strings.get(0);
    }

    assertEquals("one", firstElement);
}

Java 8

This snippet will find the first element in arraylist using java 8. The Java 8 Streams API provides Streams.findFirst which will return the wrapper Optional object describing the first element of the stream. If the arraylist is empty, an empty Optional will be returned.

@Test
public void get_first_element_in_list_with_java8 () {

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

    Optional<String> firstElement = strings.stream().findFirst();

    assertEquals("one", firstElement.orElse("two"));
}

Google Guava

Guava Iterables.getFirst will return the first element in the list or the default value if the list is empty.

@Test
public void get_first_element_in_list_with_guava () {
    List<String> strings = Lists.newArrayList("one", "two", "three");

    String firstElement = Iterables.getFirst(strings, null);

    assertEquals("one", firstElement);
}

Apache Commons

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

@Test
public void get_first_element_in_list_with_apachecommons () {
    List<String> strings = Lists.newArrayList("one", "two", "three");

    String firstElement = (String) CollectionUtils.get(strings, 0);

    assertEquals("one", firstElement);
}