Common Functional Interfaces in java.util.function
What you'll learn: You'll discover the standard functional interfaces that Java provides out-of-the-box, so you don't have to write your own from scratch.
The Built-In Toolkit
Java's java.util.function package is like a Swiss Army knife for functional programming—it contains pre-built functional interfaces for the most common use cases. Instead of creating a new functional interface every time you need to pass behavior around, you can simply use one of these ready-made options.
Why This Matters
Remember, functional interfaces enable lambdas. The Java team anticipated the most frequent patterns developers would need and created a standard library of them. This promotes code consistency and reduces boilerplate across the entire Java ecosystem.
The Core Players
The java.util.function package includes several fundamental interfaces:
- Predicate: Tests a condition and returns
trueorfalse(you've used this withfilteroperations) - Function: Transforms an input into an output (you've seen this with
map) - Consumer: Accepts an input and performs an action without returning anything (used with
forEach) - Supplier: Provides a value without taking any input (like a factory)
- UnaryOperator: Special case of
Functionwhere input and output are the same type - BinaryOperator: Combines two values of the same type into one (you've used this with
reduce)
There are also specialized versions for primitives (like IntPredicate, LongFunction) to avoid boxing overhead.
These interfaces work seamlessly with the Stream API and lambda expressions you've already been using—they're the foundation beneath features like filter, map, reduce, and collectors.
Key Takeaway: The java.util.function package provides standard functional interfaces for common patterns, eliminating the need to create custom interfaces for typical functional programming tasks and ensuring consistency across Java applications.