Java 8: Stream filter -> map -> collect pipeline

Streams process collections declaratively: keep, transform, then gather the results.

Code
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
List<Integer> squaredEvens = nums.stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * n)
        .collect(Collectors.toList());
System.out.println(squaredEvens);
Output
[4, 16, 36]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26