Given the code fragments:



public class Person {

    String name;
    int age;

    public Person(String n, int a) {
        name = n;
        age = a;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
public class Test {

    public static void checkAge(List<Person> list, Predicate<Person> predicate) {
        for (Person p : list) {
            if (predicate.test(p)) {
                System.out.println(p.name + " ");
            }
        }
    }

    public static void main(String[] args) {
        List<Person> iList = Arrays.asList(new Person("Hank", 45), new Person("Charlie", 40), new Person("Smith", 38));
        // line n1
    }
}

Which code fragment, when inserted at line n1, enables the code to print Hank?

A.

checkAge(iList, () -> p.getAge() > 40);
B.
checkAge(iList, Person p -> p.getAge() > 40);
C.
checkAge(iList, p -> p.getAge() > 40);
D.
checkAge(iList, (Person p) -> { p.getAge() > 40; });

題解

Java 8導入了Lambda語法,可以參考這篇文章來學習:

Predicate的JDK原始碼片段如下:

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);
}

要實體化Predicate類別,必須要實作test方法。選項C是正確的Lambda語法的用法,可以實作出Predicate類別的test方法。