Selects all elements from input collection which match the given predicate into an output collection. - Java java.util

Java examples for java.util:Collection Element

Description

Selects all elements from input collection which match the given predicate into an output collection.

Demo Code


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

public class Main{
    /**/*  w ww  .  jav  a2  s .  c om*/
     * Selects all elements from input collection which match the given
     * predicate into an output collection.
     * <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 all the elements of the collection which matches the
     *         predicate or [] if none could be found or null if the input
     *         collection is null.
     * @throws NullPointerException if the predicate is null.
     */
    public static <T> List<T> findAll(Iterable<T> col,
            Predicate<? super T> predicate) {
        if (col == null) {
            return null;
        }
        if (predicate == null) {
            throw new NullPointerException(
                    "The 'predicate' argument is NULL");
        }
        int size = (col instanceof Collection) ? ((Collection) col).size()
                : 0;
        ArrayList<T> result = new ArrayList<T>(size);
        for (final T item : col) {
            if (predicate.test(item)) {
                result.add(item);
            }
        }
        return result;
    }
}

Related Tutorials