Skip to lesson

Stream basics: practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most beginner stream bugs come from four habits: forgetting the terminal operation, using a stream twice, guessing the wrong order of work, and starting from the wrong source. Each one is easy to spot once you know its symptom.

Mistake 1: no terminal operation

A pipeline without a terminal operation compiles and runs, but does nothing: no element is read and no lambda runs. The symptom is a result that never changes, such as a list that still holds every element after a filter.

Java
List<String> names = new ArrayList<>(List.of(" asha", "ravi "));names.stream().map(s -> s.trim());                  // no terminal operation: nothing runsnames.stream().map(s -> s.trim()).toList();         // result thrown awayList<String> clean = names.stream().map(s -> s.trim()).toList();  // keep it

The same symptom appears when the terminal operation is there but its result is thrown away. A stream never writes back into its source, so list.stream().map(...).toList(); on its own line leaves list as it was. Always keep the result: List<String> clean = ...toList();.

Mistake 2: using a stream twice

A stream variable used for two answers fails on the second one with IllegalStateException: stream has already been operated upon or closed. The same happens when two steps are chained onto the same stream object, before any terminal operation.

Example 1 · Fix: a missing terminal operation and a stream used twice

FixBothDemo.javaJava
import java.util.List;import java.util.function.Supplier;import java.util.stream.Stream;
public class FixBothDemo {    public static void main(String[] args) {        List<String> register = List.of("P", "A", "P", "P", "A");
        // broken 1: no terminal operation, the result is lost        register.stream().filter(s -> s.equals("A"));
        // broken 2: one stream, two terminal operations        Stream<String> present = register.stream().filter(s -> s.equals("P"));        System.out.println("Present: " + present.count());        try {            System.out.println("Present list: " + present.toList());        } catch (IllegalStateException e) {            System.out.println("Second use: " + e.getMessage());        }
        // fixed: keep each result, and build a fresh stream per use        long absent = register.stream().filter(s -> s.equals("A")).count();        Supplier<Stream<String>> presentS = () -> register.stream().filter(s -> s.equals("P"));        System.out.println("Absent: " + absent);        System.out.println("Present: " + presentS.get().count() + ", list " + presentS.get().toList());    }}
Output
Present: 3
Second use: stream has already been operated upon or closed
Absent: 2
Present: 3, list [P, P, P]

What this code does

  • The first pipeline compiles but never runs, and its result has nowhere to go. The second throws on its second terminal operation.
  • The fixed code keeps every result in a variable and gets a new stream from the Supplier for each use.

The fixes do not change: call list.stream() again for each answer, keep shared steps in a Supplier<Stream<T>> or a method that returns a fresh stream, or collect the data once with toList() and reuse the list.

Mistake 3: guessing the wrong order

When you predict the output of a pipeline with prints, remember the real flow: each element runs through every step before the next one enters. Lines from different steps interleave, element by element.

Example 2 · Predict the order: a full trace

FullTraceDemo.javaJava
import java.util.stream.Stream;
public class FullTraceDemo {    public static void main(String[] args) {        Stream.of("Kabir", "Om", "Asha", "Diya", "Meera")                .filter(n -> {                    System.out.println("filter  " + n);                    return n.length() > 2;                })                .map(n -> {                    System.out.println("map     " + n);                    return n.length();                })                .limit(2)                .forEach(len -> System.out.println("forEach " + len));    }}
Output
filter  Kabir
map     Kabir
forEach 5
filter  Om
filter  Asha
map     Asha
forEach 4

What this code does

  • Kabir runs the whole pipeline first. Om fails the filter, so the next line is Asha's filter, not a map line.
  • After Asha, two elements have passed limit(2), so the stream stops: Diya and Meera are never read.

Three things change the picture. Short-circuiting steps, findFirst, anyMatch and limit, stop reading once they have their answer, so later elements never appear. A stateful step like sorted collects every element first, so all steps before it finish before any step after it starts. And since Java 9, count() may skip the steps entirely when it already knows the size.

Mistake 4: the wrong source

Stream.of(intArray) gives one element, the whole array; use Arrays.stream(intArray). A map has no stream(); stream its entrySet(), keySet() or values().

A HashSet or HashMap source has no promised order, so use a TreeSet, TreeMap or a list when the output order matters.

Example 3 · Mixed sources in one report

MixedSourcesDemo.javaJava
import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Stream;
public class MixedSourcesDemo {    public static void main(String[] args) {        List<String> hostel = List.of("Aarav", "Kabir", "Anika");        String[] subjects = {"Maths", "Physics", "Chemistry"};        int[] labHours = {4, 6, 3};        Map<String, Integer> feesDue = new TreeMap<>();        feesDue.put("Aarav", 0);        feesDue.put("Kabir", 5000);        String notice = "Exam on Monday\nBring ID card\nNo phones";
        System.out.println("Hostel names with A: "                + hostel.stream().filter(n -> n.startsWith("A")).toList());        System.out.println("Subjects over 5 letters: "                + Arrays.stream(subjects).filter(s -> s.length() > 5).count());        System.out.println("Lab hours in total: " + Arrays.stream(labHours).sum());        System.out.println("Fees pending from: " + feesDue.entrySet().stream()                .filter(e -> e.getValue() > 0)                .map(e -> e.getKey())                .toList());        System.out.println("Notice lines: " + notice.lines().count());        System.out.println("Payment modes: " + Stream.of("Card", "Cash", "Wallet").count());    }}
Output
Hostel names with A: [Aarav, Anika]
Subjects over 5 letters: 2
Lab hours in total: 13
Fees pending from: [Kabir]
Notice lines: 3
Payment modes: 3

What this code does

  • Six sources, one rule: after the source, the steps are the same filter, map and terminal operations.
  • Arrays.stream(labHours) gives an IntStream, so it has sum(); the map is streamed through entrySet(); the text through lines().

text.chars() gives int codes, so compare with 'P' or cast with (char).

The source must stay still while the stream reads it. A lambda that adds to or removes from the source list throws ConcurrentModificationException; build the change as a new list and apply it afterwards.

Example 4 · Attendance loops rewritten as streams

AttendanceStreamsDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Mark(String student, String date, boolean present) {}
public class AttendanceStreamsDemo {    public static void main(String[] args) {        List<Mark> marks = List.of(                new Mark("Aarav", "01-07", true),                new Mark("Diya", "01-07", false),                new Mark("Aarav", "02-07", true),                new Mark("Diya", "02-07", true),                new Mark("Aarav", "03-07", false),                new Mark("Diya", "03-07", false));
        // loop version: Diya's absent dates        List<String> loopDates = new ArrayList<>();        for (Mark m : marks) {            if (m.student().equals("Diya") && !m.present()) {                loopDates.add(m.date());            }        }        System.out.println("Loop   - Diya absent on: " + loopDates);
        // stream versions        List<String> diyaAbsent = marks.stream()                .filter(m -> m.student().equals("Diya"))                .filter(m -> !m.present())                .map(Mark::date)                .toList();        long aaravPresent = marks.stream()                .filter(m -> m.student().equals("Aarav"))                .filter(Mark::present)                .count();        boolean anyAbsentOn0207 = marks.stream()                .filter(m -> m.date().equals("02-07"))                .anyMatch(m -> !m.present());
        System.out.println("Stream - Diya absent on: " + diyaAbsent);        System.out.println("Aarav present days: " + aaravPresent);        System.out.println("Anyone absent on 02-07? " + anyAbsentOn0207);    }}
Output
Loop   - Diya absent on: [01-07, 03-07]
Stream - Diya absent on: [01-07, 03-07]
Aarav present days: 2
Anyone absent on 02-07? false

What this code does

  • The && inside the loop's if splits into two filter steps, m.date() becomes map(Mark::date), and add becomes toList().
  • Each question gets its own fresh pipeline from marks: a list, a count and a yes-or-no answer.

Finish up

Mark complete & continue

Next: Keep elements with filter