Functional Interfaces
Explore the concept of functional interfaces in Java by defining custom interfaces and mastering key standard ones like Predicate, Consumer, and Function. Understand how these interfaces enable lambda expressions to simplify code for conditions, actions, and transformations, enhancing functional programming skills.
In the previous lesson, we used existing interfaces like Comparator and Runnable to give our lambdas a type. We learned that a lambda can be assigned to any interface, provided that interface has exactly one abstract method.
But what if we need a behavior that doesn’t fit into Runnable (which takes nothing) or Comparator (which compares two things)? We shouldn’t have to define a new named interface for every small piece of logic we write.
Java solves this by providing a library of generic functional interfaces in java.util.function. In this lesson, we will define our own functional interface to solidify the concept, and then master the three most critical standard interfaces used in modern Java development.
Defining functional interfaces
A functional interface is defined by the single abstract method (SAM) rule: it must contain exactly one abstract method. Default and static methods do not count toward this limit, which allows functional interfaces to provide additional utility methods while remaining valid targets for lambdas.
This single method defines the function type that the lambda implements. A lambda expression can only be assigned where a functional interface is expected, because the interface provides the ...