Filter a List with Predicate - Java java.util

Java examples for java.util:List Filter

Description

Filter a List with Predicate

Demo Code


//package com.java2s;
import java.util.LinkedList;
import java.util.List;

import java.util.function.Predicate;

public class Main {
    /**/*w w w . ja v  a  2s .c  om*/
     * 
     * <pre>
     * {@code
     * filter(listOfStrings, (String str) -> !str.isEmpty());
     * 
     * IntPredicate evnNumbers = (int i) -> i % 2 == 0; //to avoid autoboxing rather than (Integer i) -> i % 2 == 0;
     * filter(listOfIntegers, evenNumbers);
     * }
     * </pre>
     * 
     * @param list
     * @param predicate
     * @return
     */
    public static <T> List<T> filter(List<T> list, Predicate<T> predicate) {
        List<T> filtered = new LinkedList<>();
        for (T entry : list) {
            if (predicate.test(entry)) {
                filtered.add(entry);
            }
        }
        return filtered;
    }
}

Related Tutorials