11.7. Functional Interfaces as Parameters

A common use of functional interfaces is to allow Java programmers to pass method definitions as parameters to other methods.

For example, we may want to write a generic method called any that returns true if at least one of the elements of an array passes a test supplied using a Predicate. The signature of that method would look like this:

public static <T> boolean any(T[] elements, Predicate<T> predicate) {
    ...
} // any

Notice that the method is generic and can be parameterized to take any reference type. Also, note that we are passing in a Predicate<T> where T must match the datatype of the provided array.

So, if we wanted to call any using an array of strings, we would need to pass in a Predicate<String> that references a test method that takes in a String and returns a boolean value.

Therefore, we can assume that predicate is a reference to an object that contains a valid test method, and we can call it in our implementation of any:

public static <T> boolean any(T[] elements, Predicate<T> predicate) {
    for (T t: elements) {
        if (predicate.test(t)) {
             return true; // return true if an element passes the test
        } // if
    } // for

    // If we make it out of the loop, no elements passed the test
    return false;
} // all

Test Yourself

  • Write a method called all that returns true if all the elements of an array pass a test supplied using a Predicate.

    public static <T> boolean all(T[] elements, Predicate<T> predicate) {
       ...
    } // all
    
  • Write a method

Test Yourself Solutions (open after attempting the questions above)
  • One possible solution:

    public static <T> boolean all(T[] elements, Predicate<T> predicate) {
        for (T t: elements) {
            if (!predicate.test(t)) {
                return false; // return false if an element doesn't pass the test
            } // if
        } // for
    
        // If we make it out of the loop, all elements passed the test
        return true;
    } // all
    
  • We won’t provide a solution to the second example above. Try it on your own, test it, and ask questions on Piazza if you get stuck. Feel free to share your code on Piazza since “Test Yourself” questions are not graded assignments.