Java examples for java.util:Collection Search
Filter an Collection using an Predicate instance. Example: The sample below is going to return a Collection that inside of it, it'll have just a single instance of a String "A Object".
import java.util.ArrayList; import java.util.Collection; import java.util.function.Predicate; public class Main { /**/* w w w. j av a 2 s. co m*/ * Filter an {@link Collection} using an {@link Predicate} instance.<br/> * Example: The sample below is going to return a {@link Collection} that inside * of it, it'll have just a single instance of a String "A Object". * * <pre> * {@link ArrayList}<String> list = new ArrayList<String>(); * list.add("A Object"); * list.add("B Object"); * * {@link Collection}<String> b = CollectionsUtils.filter(list, new {@link Predicate}<String>() { * * public boolean apply(String type) { * return (type.charAt(0) == 'A'); * }; * }); * </pre> * * @param source * Collection source to be filtered. This field is mandatory, if you * don't send it, it'll generate an {@link NullPointerException}. * @param predicate * Instance of the predicate to be used to apply the filter. This field * is mandatory, if you don't send it, it'll generate an * {@link NullPointerException}. * @return It'll returns an Collection instance filtered by the predicate. If * the <code>source</code> or the <code>predicate</code> passed through * parameter is null, it'll throw a {@link NullPointerException}. */ public static <T> Collection<T> filter(Collection<T> source, Predicate<T> predicate) { if (source == null) { throw new NullPointerException("The source is mandatory."); } if (predicate == null) { throw new NullPointerException("The predicate is mandatory."); } Collection<T> result = new ArrayList<T>(); if (source.size() > 0) { for (T element : source) { if (predicate.test(element)) { result.add(element); } } } return result; } }