JvJava
IntermediateLesson 11 of 16

Lambdas & Streams – Java

Declaratively filtering, transforming, grouping and summarizing data.

A lambda is a short anonymous function: (a, b) -> a + b. It fits any functional interface (one abstract method), e.g. Function, Predicate, Consumer, Supplier, Comparator. With Class::method you write method references.

import java.util.*;
import java.util.function.*;

Function<Integer, Integer> doppelt = x -> x * 2;
Predicate<String> leer = String::isEmpty;
BiFunction<Integer, Integer, Integer> plus = Integer::sum;
System.out.println(doppelt.apply(21) + " " + leer.test("") + " " + plus.apply(2, 3));  // 42 true 5

A stream is a pipeline: source → intermediate operations (filter, map, sorted, distinct, limit) → terminal operation (toList, collect, sum, count, forEach). Intermediate operations only run once a terminal operation is called (lazy).

import java.util.stream.*;

List<Integer> zahlen = List.of(5, 2, 8, 1, 9, 4);

List<Integer> ergebnis = zahlen.stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * n)
        .sorted()
        .toList();
System.out.println(ergebnis);                                  // [4, 16, 64]
System.out.println(zahlen.stream().mapToInt(Integer::intValue).sum());   // 29
System.out.println(zahlen.stream().anyMatch(n -> n > 8));      // true
System.out.println(Stream.of("a", "b", "c").collect(Collectors.joining(", ", "[", "]")));  // [a, b, c]

In the example, filter keeps the numbers 2, 8, 4, map squares them to 4, 64, 16, and sorted() orders them: [4, 16, 64]. With Collectors you group data – this is like GROUP BY in SQL:

record Person(String name, String stadt, int alter) {}

List<Person> leute = List.of(
        new Person("Ada", "London", 36),
        new Person("Bob", "Berlin", 25),
        new Person("Eva", "Berlin", 31));

Map<String, List<String>> proStadt = leute.stream().collect(
        Collectors.groupingBy(Person::stadt, TreeMap::new,
                Collectors.mapping(Person::name, Collectors.toList())));
System.out.println(proStadt);        // {Berlin=[Bob, Eva], London=[Ada]}

Map<String, Long> anzahl = leute.stream()
        .collect(Collectors.groupingBy(Person::stadt, Collectors.counting()));
System.out.println(anzahl.get("Berlin"));   // 2

System.out.println(leute.stream().mapToInt(Person::alter).max().getAsInt());  // 36
TipStreams are not always better than loops. Use them for transformations and evaluations, but a simple loop with side effects often stays more readable. Stream.toList() (since Java 16) returns an immutable list.
WarningA stream can only be consumed once – a second call of a terminal operation throws an IllegalStateException.