Retrieves all elements from a collection that match a predicate. - Java java.util

Java examples for java.util:Collection Element

Description

Retrieves all elements from a collection that match a predicate.

Demo Code

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

public class Main {
  /**//  w  w  w.j  a v  a2 s  .c  o m
   * Retrieves all elements from a collection that match a predicate.
   * 
   * The result will be all elements of the source collection for which the
   * predicate is true, retrieved in normal iteration order.
   * 
   * @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 A list containing all matching elements in iteration order. Never
   *         null. Can be empty.
   */
  public static <T> List<T> selectAsList(Collection<? extends T> source, Predicate<T> filter) {
    List<T> result = new ArrayList<T>();
    for (T t : source) {
      if (filter.test(t)) {
        result.add(t);
      }
    }
    return result;
  }
}

Related Tutorials