So far, methods take values. Often you want to pass behaviour: "sort by this", "keep the ones that match that", "do this when the button is pressed". A lambda is a small unnamed function you can store in a variable and pass to a method. x -> x * 2 reads "given x, give back x times 2".
A lambda needs a type, and that type is a functional interface: an interface with exactly one abstract method. The lambda becomes the body of that method. Java ships the common shapes in java.util.function:
Function<T, R>: takes a T, returns an R. Method: apply.
Predicate<T>: takes a T, returns true or false. Method: test.
Consumer<T>: takes a T, returns nothing. Method: accept.
Supplier<T>: takes nothing, returns a T. Method: get.
BiFunction<T, U, R> takes two; UnaryOperator<T> and BinaryOperator<T> are functions whose result has the same type as their input.
Java
Function<Integer, Integer> doubler = x -> x * 2;
Predicate<String> isLong = s -> s.length() > 5;
Supplier<String> greeting = () -> "hello";
BinaryOperator<Integer> add = (a, b) -> a + b;
Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!");
System.out.println(doubler.apply(21));
System.out.println(isLong.test("duck") + " " + isLong.test("platypus"));
System.out.println(greeting.get());
System.out.println(add.apply(2, 3));
shout.accept("quack");
Prints
42
false true
hello
5
QUACK!
Brackets go round the parameters when there are none or several; a body with more than one statement goes in braces with a return: (a, b) -> { int s = a + b; return s * s; }. The parameter types are worked out from the interface.
Passing behaviour to a method
The real power is writing methods that take behaviour as a parameter. One method can then do many jobs:
Java
public class Main {
static List<String> keep(List<String> xs, Predicate<String> rule) {
List<String> out = new ArrayList<>();
for (String x : xs) if (rule.test(x)) out.add(x);
return out;
}
public static void main(String[] args) {
List<String> names = List.of("Ana", "Benedict", "Cy", "Dorothea");
System.out.println(keep(names, s -> s.length() <= 3));
System.out.println(keep(names, s -> s.startsWith("D")));
Predicate<String> shortName = s -> s.length() <= 3;
System.out.println(keep(names, shortName.negate()));
}
}
Prints
[Ana, Cy]
[Dorothea]
[Benedict, Dorothea]
Functional interfaces come with helpers to combine them: negate, and and or on predicates, andThen and compose on functions. Comparator, from the last course, is a functional interface too, which is why list.sort((a, b) -> a.length() - b.length()) works.
Method references
When a lambda just calls one existing method, a method reference says it shorter with ::. String::toUpperCase means s -> s.toUpperCase(); System.out::println means x -> System.out.println(x); Integer::parseInt means s -> Integer.parseInt(s); ArrayList::new means () -> new ArrayList<>().
Java
List<String> words = new ArrayList<>(List.of("kiwi", "Apple", "fig"));
words.replaceAll(String::toLowerCase);
words.sort(Comparator.comparing(String::length));
words.forEach(System.out::println);
Function<String, Integer> parse = Integer::parseInt;
System.out.println(parse.andThen(n -> n + 1).apply("41"));
Prints
fig
kiwi
apple
42
Capturing variables
A lambda can use local variables from around it, but only ones that never change after they're set (effectively final). This won't compile, because count changes:
Won't compile
int count = 0;
names.forEach(n -> count++); // error: local variables referenced from a lambda must be final or effectively final
The rule exists because a lambda may run later, or on another thread, after the variable is gone. Use the result of a stream instead (next lesson), or an AtomicInteger if you really need a counter.
Keep lambdas short. If one grows past a couple of lines, give it a name as a method and pass a method reference: it's easier to read and to test.
Practice
What does this print?
Function<Integer, Integer> plus3 = x -> x + 3;
Function<Integer, Integer> times2 = x -> x * 2;
System.out.println(plus3.andThen(times2).apply(4));
More info
Quick reference
x -> x * 2
A lambda: given x, return x * 2.
(a, b) -> { ...; return r; }
Several parameters, a block body.
Function<T,R>.apply
T in, R out.
Predicate<T>.test
T in, boolean out; and / or / negate.
Consumer<T>.accept / Supplier<T>.get
T in, nothing out / nothing in, T out.
Class::method
A method reference: String::length, System.out::println.