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.
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 numbers = Lists.newArrayList[ new Integer[1], new Integer[2], new Integer[3]]; Optional 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.
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 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]; }Find element in list posted by Justin Musgrove on 13 March 2013
Tagged: java and java-collections
Share on: Twitter Facebook Google+