Find first non null

This example will find the first non null element in an array using java, java 8, guava and apache commons.

Straight up Java

Iterating over the collection using a for each loop an if statement will check that an element is not null. The first non null value will break out of the loop otherwise the firstNonNull variable will remain null.

@Test
public void find_first_non_null_list_java () {

    List<String> strings = new ArrayList<String>();
    strings.add(null);
    strings.add("Hello");
    strings.add(null);
    strings.add("World");

    String firstNonNull = null;
    for (String string : strings) {
        if (string != null) {
            firstNonNull = string;
            break;
        }
    }

    assertEquals("Hello", firstNonNull);
}

Java 8

This snippet will find the first non null element in an arraylist using Java 8. The Streams API contains Stream.Filter which will return elements that match a predicate. By passing a java predicate via a lambda expression, the stream will filter elements not equaling null. If any elements match the Stream.findFirst will return an java Optional that describes the element. If no elements match an empty optional will be returned.

@Test
public void find_first_non_null_list_java8_lambda () {

    List<String> strings = Lists.newArrayList(
            null,
            "Hello",
            null,
            "World");

    Optional<String> firstNonNull = strings
            .stream()
            .filter(p -> p != null)
//         .filter(Objects::nonNull)
            .findFirst();

    assertEquals("Hello", firstNonNull.get());
}

Google Guava

This snippet will show how to find the first element in an array list using guava. Passing a guava predicate returning true if an object isn't null, the Iterables.find will return the first element that matches.

@Test
public void find_first_non_null_list_guava () {

    List<String> strings = Lists.newArrayList(
            null,
            "Hello",
            null,
            "World");

    String firstNonNull = Iterables.find(strings, Predicates.notNull());

    assertEquals("Hello", firstNonNull);
}

Apache Commons

This snippet will use apache commons to find the first element in a collection. ObjectUtils.firstNonNull will return the first value in an array that isn't null. We will convert the given array list to an array by calling list.toArray.

@Test
public void find_first_non_null_list_apache () {

    List<String> strings = new ArrayList<String>();
    strings.add(null);
    strings.add("Hello");
    strings.add(null);
    strings.add("World");

    String firstNonNull = (String) ObjectUtils.firstNonNull(strings.toArray());

    assertEquals("Hello", firstNonNull);
}