Java examples for java.util:Collection First Element
Retrieves the first element from a collection that matches a predicate.
import java.util.Collection; import java.util.function.Predicate; public class Main { /**//from w w w. j av a2 s .c om * Retrieves the first element from a collection that matches a predicate. * * @param <T> * The type of elements we are interested in. * @param source * A collection containing elements we are interested in. Not null. Can * be empty. * @param filter * The predicate determining if an element is to be retrieved. Not * null. * @return The first matching element or null if no element matches. */ public static <T> T selectFirst(Collection<? extends T> source, Predicate<T> filter) { for (T t : source) { if (filter.test(t)) { return t; } } return null; } }