← Java from Scratch Lesson 87 of 88 · 10 XP

Lambda expressions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A lambda is a short way of writing an implementation of an interface with one method (a functional interface):

// before (an anonymous class):
Comparator<String> c1 = new Comparator<String>() {
    public int compare(String a, String b) { return a.length() - b.length(); }
};
// after:
Comparator<String> c2 = (a, b) -> a.length() - b.length();

Ready-made functional interfaces are in java.util.function: Function<T, R> (apply), Predicate<T> (test → boolean), Consumer<T> (accept), Supplier<T> (get), BinaryOperator<T>.

Method references are even shorter: String::length, System.out::println, Integer::sum.

Collections and the Stream API work with lambdas:

list.forEach(x -> System.out.println(x));
list.removeIf(s -> s.isEmpty());
List<Integer> evenSquares = nums.stream()
    .filter(x -> x % 2 == 0)        // keep the even ones
    .map(x -> x * x)                // square them
    .toList();                      // collect (Java 16+)
int total = nums.stream().mapToInt(Integer::intValue).sum();

Task. Read numbers. Using the Stream API and lambdas, print: the squares of the even numbers (separated by spaces), the sum of the positive ones, true/false — whether there's a number greater than 100 (anyMatch), and all the numbers transformed by a Function<Integer, String> that you build from two functions with andThen: first x * 3, then "<" + x + ">".

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.