Finds the first element in the given collection which matches the given predicate. - Java java.util

Java examples for java.util:Collection First Element

Description

Finds the first element in the given collection which matches the given predicate.

Demo Code


import java.util.function.Predicate;

public class Main {
  /**/*from   w  w  w  .j av  a 2 s.c o m*/
   * Finds the first element in the given collection which matches the given
   * predicate.
   * <p>
   *
   * @param <T>
   *          the type of object the {@link Iterable} contains.
   * @param col
   *          the collection to search, may be null.
   * @param predicate
   *          the predicate to use.
   * @return the first element of the collection which matches the predicate or
   *         null if none could be found.
   * @throws NullPointerException
   *           if the predicate is null.
   */
  public static <T> T findFirst(Iterable<T> col, Predicate<? super T> predicate) {
    if (col == null) {
      return null;
    }
    if (predicate == null) {
      throw new NullPointerException("The 'predicate' argument is NULL");
    }
    for (final T item : col) {
      if (predicate.test(item)) {
        return item;
      }
    }
    return null;
  }
}

Related Tutorials