Skip to content

Stream Pipelines

The Course
•
20 min study

A stream describes a sequence of operations over data. It is not another collection and does not store your report. Begin with the loop you already understand, then translate selection and transformation into a pipeline. Keep a loop when it explains state changes more clearly.

Work through the example

stream() creates a source. filter keeps entries satisfying a Predicate. mapToInt transforms each remaining Integer into a primitive int, and sum is the terminal operation producing a result. Intermediate operations are lazy: they run when a terminal operation consumes the stream.

Read the chain top to bottom: start with [25, -5, 10], retain [25, 10], convert the retained wrapper values to primitive ints, then add them to obtain 35. The line breaks before each dot only format one expression. mapToInt(value -> value) looks unchanged, but Java unboxes each Integer because this operation requires an int result.

The pipeline below ignores nonpositive values without editing the list. A stream can be consumed only once. Create a new stream from the collection for a second report; do not store a used stream and try to reuse it. Stream use does not make nulls, overflow or invalid domain data disappear.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<Integer> minutes = new ArrayList<>();
        minutes.add(25);
        minutes.add(-5);
        minutes.add(10);
        int total = minutes.stream()
            .filter(value -> value > 0)
            .mapToInt(value -> value)
            .sum();
        System.out.println(total);
        System.out.println(minutes);
    }
}
Check your prediction
Text
35
[25, -5, 10]

Compare the behavior

To see laziness, the filter has to show when it runs. For this demonstration only, its predicate prints the title it checks; in real code, keep predicates free of side effects. If filter ran when the pipeline is defined, the "checking" lines would come first. A Consumer is another functional interface: it accepts one value and returns no result (void). The terminal forEach applies that action to each retained value. System.out::println is a method reference compatible with that Consumer. Use forEach for a deliberate final effect, not as a substitute for every loop.

Trace the changed case Java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<String> titles = new ArrayList<>();
        titles.add("Read");
        titles.add("Go");
        Stream<String> pipeline = titles.stream()
            .filter(title -> {
                System.out.println("checking " + title);
                return title.length() >= 4;
            });
        System.out.println("Before terminal operation");
        pipeline.forEach(System.out::println);
    }
}
Check your prediction
Text
Before terminal operation
checking Read
Read
checking Go

Nothing was checked until forEach asked for values. Then each title went through the whole pipeline before the next was checked: Read was checked and printed before Go was even looked at.

Translate each stage back into an ordinary loop

Think of the pipeline as three decisions: which elements remain, how retained elements are represented, and how they are combined. filter asks a boolean question; mapToInt produces a primitive numeric value; sum combines those values. The method names do not hide new rules beyond that loop behavior.

For [25,-5,10], first write the retained sequence [25,10], then the sum 35. For empty input or a filter that matches nothing, there are no contributions and the result is zero. No preliminary get(0) is needed, which avoids a separate empty-list failure.

Intermediate operations describe work but terminal operations request a result or final action. A consumed stream cannot be reused, while the unchanged source collection can create another stream. Keep these pipelines free from hidden source edits so tracing remains possible and a later reader can choose a loop without changing the contract.

Practice independently

Exercise

Stream Pipelines: practice

Use a pipeline to sum only durations of at least 25 from [10, 25, 40], printing 65. Run the same operation on an empty list, printing 0. Preserve the input. Write the equivalent loop on paper and identify the filter and accumulator.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        System.out.println("Implement sumAtLeast");
    }
}
Hint 1: the idea

Selection comes before summation. The boundary value must remain in the stream.

Hint 2: a first step

Use filter with >= minimum, then mapToInt and sum.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<Integer> values = new ArrayList<>();
        values.add(10);
        values.add(25);
        values.add(40);
        System.out.println(sumAtLeast(values, 25));
        System.out.println(sumAtLeast(new ArrayList<Integer>(), 25));
    }

    static int sumAtLeast(List<Integer> values, int minimum) {
        return values.stream()
            .filter(value -> value >= minimum)
            .mapToInt(value -> value)
            .sum();
    }
}

Expected output:

Text
65
0

Change it and test again

Test a threshold above every entry and a threshold exactly equal to an entry. Why is zero a natural empty-sum result? Do not add printing or mutations inside filter; keep the decision pure so reordering or reviewing the pipeline stays manageable.

Explain before moving on

Which operation makes the work happen? Why do you need a new stream for a second terminal operation? Explain why streams are an alternative notation for a data transformation, not a guarantee of speed.

Was this article helpful?

Your response is saved on this device.