Executes a Function on each item in a Collection and collects all the entries for which the result of the function is equal to Boolean true. - Java java.util

Java examples for java.util:Collection Operation

Description

Executes a Function on each item in a Collection and collects all the entries for which the result of the function is equal to Boolean true.

Demo Code

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

public class Main {
  /**/*from w  w w . java2 s  .  c o m*/
   * Executes a {@link Function} on each item in a Collection and collects all the
   * entries for which the result of the function is equal to {@link Boolean}
   * <tt>true</tt>.
   *
   * @param collection
   *          the collection to process
   * @param func
   *          the Function to execute
   * @return a list of objects for which the function was true
   */
  public static List select(Collection collection, Function func) {
    List result = new ArrayList();
    for (Iterator i = collection.iterator(); i.hasNext();) {
      Object item = i.next();
      if (Boolean.TRUE.equals(func.apply(item))) {
        result.add(item);
      }
    }
    return result;
  }
}

Related Tutorials