Skip to content
The Streams API
step 1/5

Reading — step 1 of 5

Learn

~1 min readLambdas and Streams

Streams are lazy pipelines over collections. They don't replace collections — they're operations on them.

import java.util.stream.*;

List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8);

int sum = nums.stream()
    .filter(n -> n % 2 == 0)
    .mapToInt(n -> n * n)
    .sum();
// 120

Three stages:

  1. Sourcecollection.stream(), Stream.of(...), Arrays.stream(...)
  2. Intermediate ops (lazy) — filter, map, flatMap, sorted, distinct, limit, skip
  3. Terminal opforEach, collect, count, sum, reduce, findFirst, anyMatch, allMatch, min, max

Nothing runs until a terminal op is invoked.

Common collectors (java.util.stream.Collectors):

List<String> upper = list.stream().map(String::toUpperCase).collect(Collectors.toList());
Map<String, Long> counts = list.stream()
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));
String joined = list.stream().collect(Collectors.joining(", "));

Java 16+ has .toList() directly. The Collectors.toList() form still works everywhere.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…