Skip to content

Collecting Results

The Course
•
20 min study

Some pipelines should produce a collection rather than a number. Choose the terminal operation according to the ownership contract your caller needs. Stream.toList gives an unmodifiable result; Collectors.toCollection lets you choose a mutable result implementation explicitly.

Work through the example

The pipeline filters short titles and maps accepted strings to bracketed labels. map transforms one value to one value; unlike filter, it does not decide whether a value remains. toList() collects the transformed values in encounter order and does not change the source.

Keep transformations small enough to name their steps. If the lambda needs validation, error recovery and several mutations, extract a method or use a loop. Compactness is not the goal: a reader should be able to predict each intermediate sequence.

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<String> titles = new ArrayList<>();
        titles.add("Read");
        titles.add("Go");
        titles.add("Test");
        List<String> labels = titles.stream()
            .filter(title -> title.length() >= 4)
            .map(title -> "[" + title + "]")
            .toList();
        System.out.println(labels);
        System.out.println(titles);
    }
}
Check your prediction
Text
[[Read], [Test]]
[Read, Go, Test]

Compare the behavior

ArrayList::new is a constructor reference: an operation with no arguments that creates the result container when the collector needs one. Such an operation is called a supplier; ArrayList::new is equivalent here to () -> new ArrayList<String>(). The empty parentheses mean there are no parameters. collect(Collectors.toCollection(...)) requests that container explicitly. Do not assume Collectors.toList guarantees ArrayList or mutability; choose toCollection when those properties matter.

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

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("Read");
        List<String> result = source.stream()
            .map(title -> title + "!")
            .collect(Collectors.toCollection(ArrayList::new));
        result.add("Test!");
        System.out.println(result);
        System.out.println(source);
    }
}
Check your prediction
Text
[Read!, Test!]
[Read]

Predict the sequence after every transformation

For labels with surrounding spaces, write a trace row after trim, after blank filtering, and after distinct. Equal original spellings may not become equal until normalization. That is why moving distinct before trim can leave two equal final labels in the report.

A terminal collection result needs an ownership decision. toList returns an unmodifiable list; asking to add later should fail. A caller that needs an independent editable result can use toCollection(ArrayList::new). Neither approach changes the source, and neither promises deep copies of mutable elements.

Do not mix up Stream.toList with Collectors.toList: their names look alike, but the latter does not promise the same concrete list or mutability contract. Choose an explicit collector when editability matters. Verify a subsequent caller operation, not merely the initially printed list, when testing ownership.

Debug a plausible mistake

Each intermediate stage sees the values produced by the previous stage. Before trimming, " Java " and "Java" are unequal. After trimming, they represent the same requested label. Duplicate removal must operate on the representation your report promises.

Exercise

Repair the pipeline order

The report must contain one normalized Java label, printing [Java]. Keep the source unchanged. Predict what the current program actually prints before changing it, then make the smallest repair. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> source = List.of(" Java ", "Java");
        List<String> result = source.stream()
            .distinct()
            .map(String::trim)
            .toList();
        System.out.println(result);
    }
}
Hint 1: the idea

Two values can become equal only after normalization.

Hint 2: a first step

Move the normalization stage before the equality-based stage.

Show one solution
Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> source = List.of(" Java ", "Java");
        List<String> result = source.stream()
            .map(String::trim)
            .distinct()
            .toList();
        System.out.println(result);
    }
}

Expected output after repair:

Text
[Java]

The original printed [Java, Java]. distinct() compared " Java " with "Java", found them different, kept both, and only then were the spaces trimmed away. Each stage sees the previous stage's output, so trimming first means distinct() compares the values the report will actually show.

Practice independently

Exercise

Collecting Results: practice

A caller asks for the cleaned-up task titles because it wants to add to them. Write editableTitles(List<String> titles): trim each title, drop blank ones, and return a list the caller can edit, without changing the source. Then prove the choice of collector matters. In main:

  1. call editableTitles on List.of("Read", " ", " Tests "), add "Plan" to the result, and print it;
  2. print the source's size, to show it is unchanged;
  3. build the same cleaned list with .toList() instead, try to add "Plan", and print toList result is read-only when that fails.
Text
[Read, Tests, Plan]
3
toList result is read-only
Your workspace Java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> source = List.of("Read", " ", " Tests ");
        // Call editableTitles, add to its result, then compare with toList().
    }
}
Hint 1: the idea

The pipeline stages (map, filter) are the same for both lists. Only the terminal step differs, and that step decides who may change the result. The "Trace the changed case" example above shows the editable one.

Hint 2: a first step

End editableTitles with .collect(Collectors.toCollection(ArrayList::new)). For step 3, put the add call inside a try and catch UnsupportedOperationException.

Show one solution
Java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> source = List.of("Read", " ", " Tests ");

        List<String> titles = editableTitles(source);
        titles.add("Plan");
        System.out.println(titles);
        System.out.println(source.size());

        List<String> frozen = source.stream()
            .map(String::trim)
            .filter(title -> !title.isEmpty())
            .toList();
        try {
            frozen.add("Plan");
        } catch (UnsupportedOperationException error) {
            System.out.println("toList result is read-only");
        }
    }

    static List<String> editableTitles(List<String> titles) {
        return titles.stream()
            .map(String::trim)
            .filter(title -> !title.isEmpty())
            .collect(Collectors.toCollection(ArrayList::new));
    }
}

Expected output:

Text
[Read, Tests, Plan]
3
toList result is read-only

The deciding line is the terminal step. toCollection(ArrayList::new) promises a fresh ArrayList, so the caller's add works and the source (itself unmodifiable) is never touched. toList() builds the same elements but promises an unmodifiable list, so the add throws. Choose by what the caller will do with the result, not by which is shorter.

Change it and test again

Add distinct() to editableTitles and give it List.of(" Read", "Read "). Where must distinct go to return one Read? Then change editableTitles to return toList(): which line of main now fails, and is that failure in editableTitles or in its caller?

Explain before moving on

Explain the difference between map and filter. What ownership promise does toList make, and what does it not promise about mutable objects inside it?

Was this article helpful?

Your response is saved on this device.