Sub topic 5
The Core Toolkit: Function, Predicate, Consumer, and Supplier
In the last chapters you learned that every lambda needs a functional interface as its type. A functional interface is an interface with exactly one abstract method. You could write a new interface each time you need one. Most of the time you don't have to. Java already ships a set of ready-made functional interfaces in the package java.util.function.
This chapter covers the ones you will use most. You will learn what each one does, which method you call on it, and how to pick the right one for a task.
Why a Standard Toolkit Matters
Imagine every library wrote its own interface for "take a String, give back a number." One library calls it StringToInt. Another calls it Measurer. Their lambdas would not fit each other's methods, even though they do the same job.
The java.util.function package fixes this. It gives common shapes of behavior shared names. When a method asks for a Predicate<String>, every Java developer knows what kind of lambda to pass.
A shape here means two things:
- What the lambda takes in (its parameters).
- What it gives back (its return value).
Each standard interface stands for one shape.
The Six Interfaces You Will Use Most
Here are the six core interfaces. The letters T, U, and R are type parameters. A type parameter is a placeholder that you fill in with a real type, like String or Integer. By convention, T is the input type and R is the result type.
| Interface | Takes in | Gives back | Method you call | Typical use |
|---|---|---|---|---|
| `Function<T, R>` | one `T` | an `R` | `apply` | Turn one value into another |
| `Predicate<T>` | one `T` | `boolean` | `test` | Ask a yes-or-no question |
| `Consumer<T>` | one `T` | nothing | `accept` | Do something with a value |
| `Supplier<T>` | nothing | a `T` | `get` | Produce a value on demand |
| `UnaryOperator<T>` | one `T` | a `T` | `apply` | Change a value, same type out |
| `BinaryOperator<T>` | two `T`s | a `T` | `apply` | Combine two values into one |
Notice that the method names differ. A Predicate uses test, not apply. Beginners trip over this often, so keep the table handy.
Function: turn one thing into another
A Function<T, R> takes one input and returns one output. The output can be a different type from the input.
import java.util.function.Function;
public class FunctionDemo {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
System.out.println(length.apply("lambda")); // 6
}
}Here T is String and R is Integer. The lambda takes a word and returns its length.
Predicate: ask a yes-or-no question
A Predicate<T> takes one input and returns true or false. The word "predicate" comes from logic. It means a statement that is either true or false about something.
import java.util.function.Predicate;
public class PredicateDemo {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0;
System.out.println(isEven.test(4)); // true
System.out.println(isEven.test(7)); // false
}
}Predicates are perfect for filtering, for example "keep only the even numbers."
Consumer: do something, return nothing
A Consumer<T> takes one input and returns nothing. It "consumes" the value. You use it for side effects. A side effect is an action that changes something outside the lambda, like printing to the screen or adding to a list.
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Hello"); // Hello
}
}Supplier: produce a value from nothing
A Supplier<T> takes no input and returns a value. Its lambda starts with empty parentheses: () ->.
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
Supplier<String> greeting = () -> "Hello";
System.out.println(greeting.get()); // Hello
}
}A supplier is useful when you want to create a value only when it is needed. A default value or a new empty list are common examples.
UnaryOperator and BinaryOperator: same type in and out
Sometimes the input and output have the same type. Java has two shortcuts for that case:
UnaryOperator<T>is aFunction<T, T>. "Unary" means "one input."BinaryOperator<T>takes two inputs of typeTand returns aT. "Binary" means "two inputs."
UnaryOperator<T> actually extends Function<T, T>, so it is a special kind of Function. That is why you call apply on both.
All Six Together
This program uses every interface from the table. Run it and compare the output to the comments.
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public class BuiltInInterfaces {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
Predicate<Integer> isEven = n -> n % 2 == 0;
Consumer<String> printer = s -> System.out.println(s);
Supplier<String> greeting = () -> "Hello";
UnaryOperator<String> shout = s -> s.toUpperCase();
BinaryOperator<Integer> max = (a, b) -> Math.max(a, b);
System.out.println(length.apply("lambda")); // 6
System.out.println(isEven.test(4)); // true
printer.accept(greeting.get()); // Hello
System.out.println(shout.apply("hi")); // HI
System.out.println(max.apply(3, 7)); // 7
}
}Look at the line printer.accept(greeting.get());. The supplier produces "Hello", and the consumer prints it. Small pieces like these fit together easily.
Choosing the Right Interface
To pick an interface, ask two questions. Does the behavior take an input? Does it return something? The flowchart below walks through the choice.
Writing Methods That Accept Behavior
The real power shows up when your own methods take these interfaces as parameters. The caller then decides what the method does.
This method keeps some words and changes them. The caller supplies both rules as lambdas.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Toolkit {
static List<String> process(List<String> input,
Predicate<String> keep,
Function<String, String> change) {
List<String> out = new ArrayList<>();
for (String s : input) {
if (keep.test(s)) {
out.add(change.apply(s));
}
}
return out;
}
public static void main(String[] args) {
Supplier<List<String>> source =
() -> Arrays.asList("apple", "kiwi", "banana", "fig");
Consumer<String> show = s -> System.out.println("-> " + s);
List<String> result = process(source.get(),
s -> s.length() > 3,
s -> s.toUpperCase());
for (String s : result) {
show.accept(s);
}
// -> APPLE
// -> KIWI
// -> BANANA
}
}The process method knows nothing about word length or uppercase. It only knows it has a test and a change. You could call it again with s -> s.startsWith("b") and s -> s + "!" without touching the method.
Common Mistakes
Other mistakes beginners often make:
- Calling the wrong method.
isEven.apply(4)fails because aPredicatehastest, notapply. Check the table. - Giving a Supplier a parameter. A supplier takes nothing, so write
() -> "Hi", notx -> "Hi". - Returning a value from a Consumer.
Consumer<String> c = s -> s.length();compiles, but the length is thrown away. If you need the result, you want aFunction. - Mixing up Function's type order. In
Function<String, Integer>, the input comes first and the result comes second.
Exercises
Exercise
You need a lambda that checks whether a temperature, stored as an Integer, is below zero. Which interface fits, and what would the declaration look like?
Show answer
A Predicate, because the answer is yes or no. For example: Predicate<Integer> isFreezing = t -> t < 0; and you call it with isFreezing.test(-5), which returns true.
Exercise
Write a Supplier that returns a new, empty ArrayList of Strings, then call it and add one item.
Show answer
Supplier<List<String>> newList = () -> new ArrayList<>(); then List<String> list = newList.get(); list.add("first"); Each call to get() creates a fresh list. You need imports for java.util.ArrayList, java.util.List, and java.util.function.Supplier.
Exercise
BinaryOperator<Integer> and BiFunction<Integer, Integer, Integer> both take two Integers and return an Integer. Why might you choose BinaryOperator?
Show answer
BinaryOperator<Integer> says the same thing with one type argument instead of three, so it is shorter and clearer. It also tells readers that both inputs and the output share one type. BinaryOperator<T> extends BiFunction<T, T, T>, so it works anywhere that BiFunction is expected.
Exercise
What is wrong with this line, and how do you fix it? Consumer<String> upper = s -> s.toUpperCase(); System.out.println(upper.accept("hi"));
Show answer
A Consumer returns nothing, so accept gives back no value that println can print, and the line does not compile. If you want the uppercase result, use UnaryOperator<String> upper = s -> s.toUpperCase(); and print upper.apply("hi"), which prints HI.