Stream Pipelines

A stream pipeline describes how to process a source of values. Intermediate operations shape the data, and a terminal operation produces a result.

Streams do not store elements. The list remains the source, while sorted and forEach describe one traversal of it.

Describe a data pipeline

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> scores = List.of(82, 67, 91);
        scores.stream()
                .sorted()
                .forEach(System.out::println);
    }
}

Output:

67
82
91

sorted puts the elements in their natural order: numeric order for numbers, dictionary order for strings. Pass a Comparator when you need a different rule. The terminal forEach then prints each one.

Count what passes

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> scores = List.of(82, 67, 91);
        long passed = scores.stream()
                .filter(score -> score >= 70)
                .count();
        System.out.println(passed);
    }
}

Output:

2

filter is an intermediate operation that keeps only the elements its lambda accepts (the next lesson covers it in detail). count is a terminal operation that returns how many elements reached it, as a long.

Intermediate operations are lazy. Nothing is processed until a terminal operation such as count, toList, or forEach runs.

Create a stream and count color names with more than four letters.