AnyCompiler

Lambdas and Streams

A lambda expression, written params -> expression, is a compact way to implement a functional interface — an interface with exactly one abstract method — inline, without writing a separate named class. Greeter below has one method, greet(), so a lambda can implement it directly.

public class Main {
    interface Greeter {
        String greet(String name);
    }

    public static void main(String[] args) {
        Greeter greeter = name -> "Hello, " + name + "!";
        System.out.println(greeter.greet("Java"));
    }
}
Output
Hello, Java!

The Stream API

A stream lets you chain operations like filter and map over a collection, finishing with a terminal operation like collect to produce a result. numbers.stream().filter(...).map(...).collect(...) reads almost like a description of the transformation itself — keep the even numbers, double them, collect the result into a list.

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

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);
        List<Integer> doubled = numbers.stream()
            .filter(n -> n % 2 == 0)
            .map(n -> n * 2)
            .collect(Collectors.toList());
        System.out.println(doubled);
    }
}
Output
[4, 8]

Next: static and final — class-level members, and marking something as unchangeable.

Practice exercise

Given List<Integer> numbers containing 1, 2, 3, 4, use a stream to build a new list with each number squared, then print it.