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 the first value in an array that matches a given predicate. Your task is to complete the header of that method.

Complete the following file:

GenericUtil.java

public class GenericUtil { /** Finds first match. @param value an array of values @param pred a predicate @return the first value for which pred is true */ public static <T> ... findFirstMatch(... values, ... pred) { for (T value : values ) if (pred.invoke(value)) return value; return null; } }

Use the following files:

GenericUtilTester.java

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 = { 3, 5, 7, 9, 4, 6, 8 };
      Integer first1 = GenericUtil.findFirstMatch(values1, isEven);
      System.out.println(first1);
      System.out.println("Expected: 4"); 

      Predicate<String> isLong = new Predicate<String>()
         {
            public boolean invoke(String value)
            {
               return value.length() > 6;
            }
         };
         
      String[] values2 = { "Mary", "had", "a", "little", "lamb" };
      String first2 = GenericUtil.findFirstMatch(values2, isLong);
      System.out.println(first2);
      System.out.println("Expected: null");       
   }
}

Predicate.java

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