Recall that a predicate is a method with a Boolean return value. The Predicate interface can be used to test whether a value fulfills a property. A class implementing this interface provides an invoke method for carrying out a particular test.

The GenericUtil class contains a generic static method that finds all values in an array that match a given predicate. Your task is to implement that method.

Complete the following file:

GenericUtil.java

import java.util.List; public class GenericUtil { /** Finds all values in an array that fulfill a given predicate. @param values an array of values @param pred a predicate @return a list of values that match the predicate */ public static <T> List<T> findAllMatches(T[] values, Predicate<T> pred) { ... } }

Use the following files:

GenericUtilTester.java

import java.util.List;

public class GenericUtilTester
{
   public static void main(String[] args)
   {
      Predicate<Integer> isEven = new Predicate<Integer>()
         {
            public boolean invoke(Integer value)
            {
               return value % 2 == 0;
            }
         };
         
      Integer[] values1 = { 1, 4, 9, 16, 25, 36, 49 };
      List<Integer> matches1 = GenericUtil.findAllMatches(values1, isEven);
      System.out.println(matches1);
      System.out.println("Expected: [4, 16, 36]"); 

      Predicate<String> isShort = new Predicate<String>()
         {
            public boolean invoke(String value)
            {
               return value.length() <= 3;
            }
         };
         
      String[] values2 = { "Mary", "had", "a", "little", "lamb" };
      List<String> matches2 = GenericUtil.findAllMatches(values2, isShort);
      System.out.println(matches2);
      System.out.println("Expected: [had, a]");       
   }
}

Predicate.java

public interface Predicate<T>
{
   boolean invoke(T value);
}