I've come across many questions in regards of Java8 in-built Functional Interfaces, including this, this, this and this. But all ask about "why only one method?" or "why do I get a compilation error if I do X with my functional interface" and alike. My question is: what is the existential purpose of these new Functional Interfaces, when I can use lambdas anyway in my own interfaces?
Consider the following example code from oracle documentation:
// Approach 6: print using a predicate
public static void printPersonsWithPredicate(List<Person> roster,
Predicate<Person> tester) {
for (Person p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
OK, great, but this is achievable with their own example just above (an interface with a single method is nothing new):
// Approach 5:
public static void printPersons(<Person> roster,
CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
interface CheckPerson {
boolean test(Person p);
}
I can pass a lambda to both methods.
1st approach saves me one custom interface. Is this it?
Or are these standard functional interfaces (Consumer, Supplier, Predicate, Function) are meant to serve as a template for code organization, readability, structure, [other]?
printPersons. But can you easily implement the method's behavior with it? Example:roster.stream().filter(tester).forEach(System.out::println)CheckPersonisn't really a good name for its purpose, although that's subjective.Predicatedefinesor(Predicate),and(Predicate),negate().FunctiondefinesandThenandcompose, etc. It's not particularly exciting, until it is: using methods other than abstract ones on functions allows for easier composition, strategy selections and many more.