The functional interfaces
Java does not let a lambda name its own type, so the type comes from an interface, and java.util.function holds the ones the JDK itself uses. Six of them cover almost every lambda a program writes: one that takes a value and returns one, one that takes two, one that takes a value and returns nothing, one that takes nothing, one that returns a boolean and one that takes and returns the same type.
The six interfaces
Each line of the program declares one and calls it, so the shape of the interface is visible in the lambda:
import java.util.function.BiFunction;
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 Six {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
System.out.println(length.apply("hello"));
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(2, 3));
Consumer<String> print = s -> System.out.println("[" + s + "]");
print.accept("consumer");
Supplier<String> greeting = () -> "supplied";
System.out.println(greeting.get());
Predicate<Integer> even = n -> n % 2 == 0;
System.out.println(even.test(4) + " " + even.test(5));
UnaryOperator<Integer> twice = n -> n * 2;
System.out.println(twice.apply(21));
}
}
javac -Xlint:all Six.java
java Six
5
5
[consumer]
supplied
true false
42
The method names are the part to remember: apply for a function, accept for a consumer, get for a supplier and test for a predicate. The two fives come from two different interfaces, which is why the same body would fit either one: the context decides.
andThen and compose
Function has two methods that build a new function from two. f.andThen(g) applies f first and g to its result; f.compose(g) applies g first. The program shows the two orders on the same pair, then the pair swapped:
import java.util.function.Function;
public class Compose {
public static void main(String[] args) {
Function<String, String> twice = s -> s + s;
Function<String, String> bang = s -> s + "!";
System.out.println(twice.andThen(bang).apply("ab"));
System.out.println(twice.compose(bang).apply("ab"));
System.out.println(bang.andThen(twice).apply("ab"));
System.out.println(bang.compose(twice).apply("ab"));
}
}
javac -Xlint:all Compose.java
java Compose
abab!
ab!ab!
ab!ab!
abab!
The first line doubles ab and then adds the bang, and the second adds the bang first so both copies have it. The last two lines are the same two functions in the other order, and their results are the first two in the other order: the four lines are the four combinations. compose reads backwards from the code and forwards from the mathematics, which is why it is used less than andThen.
Methods that take a function
A method whose parameter is one of the six is generic over the behaviour. The three below take a function, a consumer and a supplier, and one more sums the result of the first:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class Higher {
public static void main(String[] args) {
List<String> words = List.of("pear", "fig", "apple");
System.out.println(map(words, s -> s.length()));
System.out.println(map(words, String::toUpperCase));
each(words, w -> System.out.print(w + " "));
System.out.println();
System.out.println(repeat(() -> "tick", 3));
System.out.println(sum(map(words, s -> s.length())));
}
static <T, R> List<R> map(List<T> input, Function<T, R> f) {
List<R> result = new ArrayList<>();
for (T value : input) {
result.add(f.apply(value));
}
return result;
}
static <T> void each(List<T> input, Consumer<T> action) {
for (T value : input) {
action.accept(value);
}
}
static <T> List<T> repeat(Supplier<T> supplier, int times) {
List<T> result = new ArrayList<>();
for (int i = 0; i < times; i++) {
result.add(supplier.get());
}
return result;
}
static int sum(List<Integer> numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
}
javac -Xlint:all Higher.java
java Higher
[4, 3, 5]
[PEAR, FIG, APPLE]
pear fig apple
[tick, tick, tick]
12
The second call is a method reference, String::toUpperCase, which is a lambda written shorter and is the subject of lesson 084. The last line reuses the first result and sums it: map is a function, and its output is data like any other.
The shape of the name
The names are systematic, and reading one is reading its signature. A Function<T, R> takes a T and returns an R; add Bi and it takes two arguments; Int, Long and Double before the name mean the argument or the result is a primitive, as IntFunction and ToIntFunction; Unary and Binary mean the argument and the result are the same type.
A method that takes a function can therefore be written against the smallest interface that fits. The filter of lesson 082 takes a Predicate and not a Function<T, Boolean>, because the two say different things to a reader and only one of them boxes the result.
Exercises
- Write a BinaryOperator<Integer> for the maximum and print the result for two numbers.
- Compose a function that trims a string with one that appends a full stop, in both orders.
- Use each to print the lengths of the words as numbers.
- Write a method that takes a Predicate and a supplier and repeats the supplier while the predicate accepts the value.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which method does a Consumer declare?
Answer
accept
A consumer takes a value and returns nothing, so its method is accept.
-
What does
f.andThen(g)do?Answer
Applies f and then g to its result
andThen reads left to right, and compose reads the other way.
-
Which interface takes no argument and returns a value?
Answer
Supplier
get() takes nothing, which is what makes a supplier a source of values.
-
What does this program print?
import java.util.function.Function; public class Q1 { public static void main(String[] args) { Function<Integer, Integer> plusOne = n -> n + 1; Function<Integer, Integer> timesTwo = n -> n * 2; System.out.println(plusOne.andThen(timesTwo).apply(3)); System.out.println(timesTwo.compose(plusOne).apply(3)); } }Answer
8 / 8
Both orders add one and then double, which is eight for three.
-
What does this program print?
import java.util.function.Predicate; public class Q2 { public static void main(String[] args) { Predicate<String> shortWord = s -> s.length() < 4; Predicate<String> startsWithA = s -> s.startsWith("a"); System.out.println(shortWord.and(startsWithA).test("ape")); System.out.println(shortWord.or(startsWithA).test("apple")); } }Answer
true / true
ape is short and starts with a; apple is not short but does start with a, so or is true.
-
What does this program print?
import java.util.function.BiFunction; public class Q3 { public static void main(String[] args) { BiFunction<String, String, String> join = (a, b) -> a + "-" + b; System.out.println(join.apply("x", "y")); } }Answer
x-y
The lambda joins the two arguments with a hyphen.
-
What does this program print?
import java.util.function.Supplier; public class Q4 { public static void main(String[] args) { int n = 3; Supplier<Integer> next = () -> n + 1; System.out.println(next.get()); System.out.println(next.get()); } }Answer
4 / 4
The supplier captures the value of n and computes the same result each time.
-
What does this program print?
import java.util.function.UnaryOperator; public class Q5 { public static void main(String[] args) { UnaryOperator<String> bang = s -> s + "!"; System.out.println(bang.andThen(bang).apply("a")); } }Answer
a!!
The first bang adds one mark and the second adds another to the result.
-
Why does a filter method take a Predicate rather than a Function of Boolean?
Answer
The predicate says it returns a condition, and no boxing is needed
The name is documentation, and the primitive result avoids a boxed Boolean.
-
What does
String::toUpperCasemean in the argument of map?Answer
A method reference that is a Function from a String to a String
The reference is a lambda that calls the instance method on its argument.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev