Search⌘ K
AI Features

Functional Interfaces

Explore the concept of functional interfaces in Java, focusing on defining custom interfaces and mastering key standard interfaces such as Predicate, Consumer, and Function. Understand how these single abstract method interfaces enable versatile lambda expressions, improving code readability and compatibility with Java's Stream API. This lesson will help you confidently implement various behaviors without creating numerous interfaces, enhancing your functional programming skills in Java.

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 ...