← 返回课程: Java from scratch

Lambdas and streams

视频即将上线

Until now, to walk through a list, filter it or transform it you wrote for loops with helper variables. Java 8 added two tools that let you express those tasks in a shorter, more declarative way: lambda expressions and streams. A lambda is an anonymous function you can pass around like data; a stream is a pipeline of operations over a sequence of elements. Together they are the modern style of processing collections in Java.

Lambdas and functional interfaces

A functional interface is an interface with a single abstract method, such as Comparator, Runnable or Predicate. A lambda is a compact way to implement it: (parameters) -> expression. The compiler infers the types. The most used ones in java.util.function are Predicate<T> (takes a value and returns boolean), Function<T, R> (turns T into R), Consumer<T> (does something with T and returns nothing) and Supplier<T> (produces a T). A method reference such as String::length is an even shorter lambda when you only call an existing method. A lambda can read local variables of the surrounding method, but only if they are not modified afterwards (they are effectively final).

java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        Predicate<Integer> isEven = n -> n % 2 == 0;
        Function<String, Integer> length = s -> s.length();
        Function<String, String> shout = s -> s.toUpperCase() + "!";
        Supplier<String> greeting = () -> "Hello";

        System.out.println(isEven.test(10));        // true
        System.out.println(length.apply("lambda")); // 6
        System.out.println(shout.apply("hey"));     // HEY!
        System.out.println(greeting.get());         // Hello

        List<String> names = new ArrayList<>(List.of("Marta", "Ana", "Luis"));
        names.forEach(n -> System.out.println("Hi " + n));
        names.removeIf(n -> n.length() < 4);
        names.sort((a, b) -> b.compareTo(a));       // descending
        System.out.println(names);                  // [Marta, Luis]
        names.forEach(System.out::println);         // method reference

        int base = 100;                             // effectively final
        Function<Integer, Integer> addBase = x -> x + base;
        System.out.println(addBase.apply(5));       // 105
    }
}

Streams: filter, transform, group

A stream is created with list.stream() and has three parts: a source, intermediate operations that return another stream (filter, map, sorted, distinct, limit) and a terminal operation that produces the result (collect, toList, count, sum, forEach, anyMatch). Nothing runs until the terminal one arrives. A stream does not modify the original collection and cannot be reused after being consumed. For numbers there are IntStream and mapToInt, with sum, average and max. Collectors.groupingBy groups into a map, and Collectors.joining joins texts. Streams make code more readable when the logic is filter and transform; if the classic loop is clearer, use it without guilt.

java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    record Employee(String name, String department, double salary) { }

    public static void main(String[] args) {
        List<Integer> numbers = List.of(5, 12, 8, 3, 20, 7, 12);

        List<Integer> evenSquares = numbers.stream()
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .distinct()
                .sorted()
                .toList();                                  // Java 16+
        System.out.println(evenSquares);                    // [64, 144, 400]

        System.out.println(numbers.stream().mapToInt(Integer::intValue).sum());  // 67
        System.out.println(numbers.stream().anyMatch(n -> n > 15));              // true
        System.out.println(numbers.stream().count());                            // 7

        List<Employee> staff = List.of(
            new Employee("Ana", "IT", 3000),
            new Employee("Luis", "IT", 2500),
            new Employee("Marta", "HR", 2800));

        Map<String, List<String>> namesByDept = staff.stream()
            .collect(Collectors.groupingBy(Employee::department,
                     Collectors.mapping(Employee::name, Collectors.toList())));
        System.out.println(namesByDept.get("IT"));          // [Ana, Luis]

        double avg = staff.stream().mapToDouble(Employee::salary).average().orElse(0);
        System.out.println(avg);                            // 2766.666...

        String joined = staff.stream().map(Employee::name).collect(Collectors.joining(", "));
        System.out.println(joined);                         // Ana, Luis, Marta

        staff.stream().max((a, b) -> Double.compare(a.salary(), b.salary()))
             .ifPresent(e -> System.out.println("Top: " + e.name()));   // Top: Ana
    }
}
  • A stream is not a collection: it holds no data, it only describes how to process it.
  • Trying to use the same stream twice throws IllegalStateException; create a new one.
  • Intermediate operations are lazy: without a terminal operation nothing happens.
  • map transforms each element; filter decides which ones pass; flatMap flattens lists of lists.
  • toList() returns an immutable list; for a modifiable one use collect(Collectors.toList()) or new ArrayList<>(...).
  • A long multi-line lambda is a sign you should extract it into a named method and use a method reference.

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →