Enrol to start learning
Reading is open to everyone. Enrolling is free, and it is what unlocks the audio lessons, practice tests and progress tracking.
22.4. Built-in Functional Interfaces (java.util.function)
Learn content
Interactive Audio Lesson
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Today, we're exploring the built-in functional interfaces found in the java.util.function package. These interfaces allow us to write cleaner and more efficient code using lambda expressions.
What exactly is a functional interface?
Great question! A functional interface is an interface that contains exactly one abstract method. This allows us to use lambda expressions to implement that method.
Can you give us an example?
Sure! Think of Predicate<T>: it takes one argument and returns a boolean. An example is x -> x > 10, which checks if a number is greater than 10.
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Let's go through each functional interface. Starting with Function<T,R>, it maps a value of type T to a value of type R.
How would you use that in code?
An example of that would be s -> s.length(), which takes a string and returns its length.
What about Consumer<T>?
Good point! Consumer<T> takes in a value and doesn’t return anything. For instance, s -> System.out.println(s) prints the string.
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Now, we have Supplier<T>, which provides a value without taking any arguments. For example, () -> new Random().nextInt().
That sounds handy for generating random numbers!
Absolutely! Then there's UnaryOperator<T>, which takes one argument of type T and returns a value of the same type. For instance, x -> x * x.
And what about BinaryOperator<T>?
Exactly! It takes two arguments of type T and returns a single result. An example is (x, y) -> x + y, which sums two numbers.
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Lastly, let’s talk about how we can use these interfaces effectively. We can pass these functional interfaces as arguments to methods.
Like in the Streams API?
Precisely! The Streams API heavily utilizes functional interfaces, allowing operations like filtering and mapping with ease.
So Predicate can filter elements of a stream?
Yes! And Function can transform the data as needed, making our code declarative and clear.
Overview
Medium Summary
This section discusses the pre-defined functional interfaces available in the java.util.function package, each serving a distinct purpose. It includes examples of lambda expressions that correspond to each interface, making it easier for developers to use them efficiently in Java applications.
Detailed Summary
Built-in Functional Interfaces (java.util.function)
In Java 8, the java.util.function package was introduced, encompassing a variety of built-in functional interfaces that are vital for functional programming. These interfaces enable developers to pass behaviors, simplifying code and enhancing readability. The primary built-in functional interfaces include:
- Predicate
: Represents a boolean-valued function of one argument. Example: x -> x > 10 - Function<T,R>: Encapsulates a function that accepts one argument of type T and produces a result of type R. Example:
s -> s.length() - Consumer
: Represents a function that takes an argument and returns no result. Example: s -> System.out.println(s) - Supplier
: Takes no arguments and returns a result. Example: () -> new Random().nextInt() - UnaryOperator
: A specialized form of Function that takes a single argument and returns an object of the same type. Example: x -> x * x - BinaryOperator
: Represents a function that takes two arguments of the same type and returns a result of the same type. Example: (x, y) -> x + y
Each of these interfaces plays a crucial role in writing concise and clear functional code, allowing developers to leverage lambda expressions efficiently.
Reference YouTube Videos
Audio Book
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountJava provides a set of pre-defined functional interfaces in the java.util.function package.
Detailed Explanation
In Java, especially with the introduction of functional programming in Java 8, pre-defined functional interfaces simplify many programming tasks. These interfaces are designed to work seamlessly with lambda expressions, making it easier to create concise and readable code.
Examples & Analogies
Think of built-in functional interfaces like common kitchen appliances—each is designed for a specific task like blending, chopping, or baking. Just as using an appliance saves time and effort in cooking, using built-in functional interfaces saves time in programming by providing ready-made solutions to common problems.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountInterface Description: Returns boolean value Example Lambda Expression: x -> x > 10
Detailed Explanation
The Predicate interface represents a single argument function that returns a boolean value. It is commonly used for testing or filtering conditions. For example, the lambda expression 'x -> x > 10' is a predicate that checks if a number is greater than 10.
Examples & Analogies
Imagine you're sorting through a group of fruits, and you only want to keep the ones that are ripe. The Predicate acts like your personal criteria for selecting fruits, only allowing through those that meet your conditions—just like the predicate checks whether a condition is true or false.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountInterface Description: Takes T, returns R Example Lambda Expression: s -> s.length()
Detailed Explanation
The Function interface takes an input of type T and produces an output of type R. For instance, the lambda expression 's -> s.length()' takes a string and returns its length, effectively transforming the input into a different output.
Examples & Analogies
Consider a vending machine: you insert a coin (input) and select a drink (output). The Function interface is like the vending machine's operation, transforming one type of item (money) into another type (a drink) so that you can enjoy the result.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountInterface Description: Takes T, returns void Example Lambda Expression: s -> System.out.println(s)
Detailed Explanation
The Consumer interface represents an operation that takes a single input argument and returns no output (void). The example 's -> System.out.println(s)' takes a string input and prints it to the console, demonstrating how a consumer performs an action without producing a result.
Examples & Analogies
Think of a teacher giving a lecture. The teacher (consumer) speaks and shares information (input) with students but does not receive any output from the students during the lecture—like how the Consumer interface operates.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountInterface Description: Returns T, takes nothing Example Lambda Expression: () -> new Random().nextInt()
Detailed Explanation
The Supplier interface is a functional interface that supplies a result without taking any input. The lambda expression '() -> new Random().nextInt()' demonstrates this by generating a random integer when called.
Examples & Analogies
A lightbulb is like a Supplier: it provides light (output) whenever the switch is turned on, without needing any inputs. Just as the Supplier generates a value when used, the lightbulb illuminates a room without needing anything to be fed into it.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountInterface Description: Takes T and returns T Example Lambda Expression: x -> x * x
Detailed Explanation
The UnaryOperator interface is a specialized form of Function that takes one argument of type T and returns a result of the same type. For example, the lambda expression 'x -> x * x' takes a number and returns its square.
Examples & Analogies
Imagine a mirror reflecting your image back to you; it takes what it sees (input) and returns the same image (output), just transformed in a way. Similarly, the UnaryOperator takes one type of input and modifies or transforms it into the same type of output.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountInterface Description: Takes (T, T) and returns T Example Lambda Expression: (x, y) -> x + y
Detailed Explanation
The BinaryOperator interface is another special case of Function; it takes two arguments of the same type and produces a result of that type. An example is the lambda expression '(x, y) -> x + y', which adds two integers.
Examples & Analogies
Think of a couple deciding to combine their savings for a vacation. Each partner brings their money (inputs), and together they have a total amount (output). The BinaryOperator behaves similarly by taking two inputs and producing a single output based on an operation, like addition.
--
Key concepts
Core takeaways and short definitions to help you quickly recall the key ideas from this section.
- Built-in Functional Interfaces:
Java 8 provides several functional interfaces that facilitate functional programming.
Predicate
: A functional interface that returns a boolean based on one input. Function<T,R>: Converts one input of type T into an output of type R.
Consumer
: Processes an input without returning a result. Supplier
: Produces a result without taking any input. UnaryOperator
: An operator that takes one argument and returns a result of the same type. BinaryOperator
: An operator that takes two inputs of the same type and returns a result.
Examples
Step-by-step examples to apply the section's ideas and test your understanding.
Predicate Example: Predicate<Integer> isGreaterThan10 = x -> x > 10;
Function Example: Function<String, Integer> stringLength = s -> s.length();
Consumer Example: Consumer<String> printString = s -> System.out.println(s);
Supplier Example: Supplier<Double> randomValue = () -> Math.random();
UnaryOperator Example: UnaryOperator<Integer> square = x -> x * x;
BinaryOperator Example: BinaryOperator<Integer> add = (x, y) -> x + y;
Memory aids
Imagine a shopkeeper (Supplier) that gives you fruits without asking what you want, while a judge (Predicate) decides if you can take a fruit based on its ripeness.
Fabulous People Can Supply Unique Beverages: Predicate, Function, Consumer, Supplier, Unary Operator, Binary Operator.
Flash Cards
Glossary
Predicate<T>
A functional interface that represents a function that takes one argument and returns a boolean value.
Function<T,R>
A functional interface that accepts one argument of type T and produces a result of type R.
Consumer<T>
A functional interface that takes a single argument and returns no result.
Supplier<T>
A functional interface that does not take any input but provides a result of type T.
UnaryOperator<T>
A functional interface that takes one argument of type T and returns a value of type T.
BinaryOperator<T>
A functional interface that takes two arguments of the same type and returns a result of the same type.