Find element in list

This example will find the first element in a arraylist that satisfies a given predicate using java, java 8, guava and apache commons.

Straight up Java

Iterating over the collection using a standard for loop an if statement will check for matching element of 3. If a match is found, then the value variable will be set.

@Test
public void find_elements_in_list_with_java () {

    List <Integer> numbers = Lists.newArrayList(
            new Integer(1),
            new Integer(2),
            new Integer(3));

    Integer value = null;
    for (Integer number : numbers) {
        if (number == 3) {
            value = number;
        }
    }
    assertEquals(new Integer(3), value);
}

Java 8

Using Java 8 this snippet will find the first element in an array list. Java 8 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 any elements that match a value of 3. 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_elements_in_list_with_java8_lambda () {

    List <Integer> numbers = Lists.newArrayList(
            new Integer(1),
            new Integer(2),
            new Integer(3));

    Optional<Integer> value = numbers
            .stream()
            .filter(a -> a == 3)
            .findFirst();

    assertEquals(new Integer(3), value.get());
}

Google Guava

This snippet will show how to find the first element in an arraylist using guava. Guava's Iterables.find will return the first element that matches the supplied guava predicate equaling 3.

@Test
public void find_elements_in_lists_with_guava () {

    List <Integer> numbers = Lists.newArrayList(
            new Integer(1),
            new Integer(2),
            new Integer(3));

    Integer value = Iterables.find(numbers, new Predicate<Integer> () {
        public boolean apply(Integer number) {
            return number == 3 ;
        }
    });

    assertEquals(new Integer(3), value);
}

Apache Commons

Similar to the examples above, this snippet will use apache commons to find the first element in a collection by passing a apache predicate to CollectionUtils.find method.

@Test
public void find_elements_in_list_with_apachecommons () {

    List <Integer> numbers = Lists.newArrayList(
            new Integer(1),
            new Integer(2),
            new Integer(3));

    Integer value = (Integer) CollectionUtils.find(numbers, new org.apache.commons.collections.Predicate() {
        public boolean evaluate(Object number) {
            return ((Integer)number).intValue() == 3 ;
        }
    });

    assertEquals(new Integer(3), value);
}