Terminal operations: 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.
Every stream ends with one terminal operation, and picking the right one is most of the work. Most bugs in this module come from three places: the empty case, the identity of reduce, and a result list that cannot change.
Pick the right terminal operation
Start from the question the code must answer, then pick the operation that answers exactly that. A wrong choice usually still compiles; it just does more work or answers a slightly different question.
Example 1 · One exam batch, every terminal operation
import java.util.Comparator;import java.util.List;
record Result(String name, int marks) {}
public class ExamReportDemo { public static void main(String[] args) { List<Result> results = List.of( new Result("Aarav", 72), new Result("Priya", 94), new Result("Rohan", 31), new Result("Kavya", 88), new Result("Divya", 59));
long passed = results.stream().filter(r -> r.marks() >= 35).count(); Result top = results.stream().max(Comparator.comparingInt(Result::marks)).get(); Result low = results.stream().min(Comparator.comparingInt(Result::marks)).get(); boolean anyFail = results.stream().anyMatch(r -> r.marks() < 35); boolean allValid = results.stream().allMatch(r -> r.marks() >= 0 && r.marks() <= 100); String firstDistinction = results.stream() .filter(r -> r.marks() >= 75) .map(Result::name) .findFirst() .orElse("none"); int total = results.stream().mapToInt(Result::marks).sum(); List<String> needHelp = results.stream() .filter(r -> r.marks() < 60) .map(Result::name) .toList();
System.out.println("Passed: " + passed + " of " + results.size()); System.out.println("Topper: " + top.name() + " " + top.marks()); System.out.println("Lowest: " + low.name() + " " + low.marks()); System.out.println("Any fail: " + anyFail + ", all marks valid: " + allValid); System.out.println("First distinction: " + firstDistinction); System.out.println("Class average: " + (total / (double) results.size())); System.out.println("Extra classes for: " + needHelp); }}Passed: 4 of 5 Topper: Priya 94 Lowest: Rohan 31 Any fail: true, all marks valid: true First distinction: Priya Class average: 68.8 Extra classes for: [Rohan, Divya]
What this code does
- Each line answers one question with the operation built for it:
countfor how many,maxandminfor the best and worst, match operations for yes or no,findFirstfor one element,sumfor a total andtoListfor a list. - Each pipeline calls
results.stream()again. A stream can be used once, but the list can make as many streams as you need.
- How many?
count(). The best by some field?min(cmp)ormax(cmp). - Yes or no?
anyMatch,allMatchornoneMatch. Just one matching element?findFirst(), orfindAny()when any will do. - One combined value?
mapToInt(...).sum()for totals,reducefor your own rule. - A list or an array?
toList(),Collectors.toCollection(ArrayList::new)ortoArray(String[]::new). Only an action?forEach.
Mistake 1: forgetting the empty case
Every terminal operation has an answer for an empty stream, and each one is different. count() gives 0. min, max, findFirst and the one-argument reduce give Optional.empty, and calling get() on it throws NoSuchElementException. reduce with an identity returns the identity.
Example 2 · Validating a batch of exam results
import java.util.ArrayList;import java.util.List;
record Result(String roll, int marks) {}
public class BatchCheckDemo { static List<String> problems(List<Result> batch) { List<String> found = new ArrayList<>(); if (batch.isEmpty()) { found.add("batch is empty"); return found; } if (!batch.stream().allMatch(r -> r.marks() >= 0 && r.marks() <= 100)) { batch.stream() .filter(r -> r.marks() < 0 || r.marks() > 100) .map(r -> "bad marks for " + r.roll()) .forEach(found::add); } long rolls = batch.stream().map(Result::roll).distinct().count(); if (rolls != batch.size()) { found.add("duplicate roll numbers"); } return found; }
public static void main(String[] args) { List<Result> good = List.of(new Result("R1", 67), new Result("R2", 81)); List<Result> bad = List.of(new Result("R1", 67), new Result("R2", 108), new Result("R1", 40));
System.out.println("Good batch: " + problems(good)); System.out.println("Bad batch: " + problems(bad)); System.out.println("Empty batch: " + problems(List.of())); }}Good batch: [] Bad batch: [bad marks for R2, duplicate roll numbers] Empty batch: [batch is empty]
What this code does
- The empty check comes first, because
allMatchwould saytruefor an empty batch.allMatchthen gives a quick yes or no, andfilterlists the exact rolls with bad marks. distinct().count()counts unique roll numbers; if it is smaller than the batch size, a roll number repeats.forEach(found::add)is fine here because the stream is sequential and only feeds a local list;toList()would be the usual choice.
allMatch and noneMatch return true; anyMatch returns false.
Real data is empty more often than you expect: a new class with no results yet, a filter that matches nothing, a file that failed to load. Test that case on purpose, and read Optional results with orElse or ifPresentOrElse.
Mistake 2: a wrong identity or a mutable result
The identity of reduce must be neutral: 0 for a sum, 1 for a product. A sum that starts at 1 is quietly one too high; a product that starts at 0 is always 0. Neither throws an error.
Example 3 · Mistakes: wrong identity, get() on empty, changing toList()
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class ThreeFixesDemo { public static void main(String[] args) { List<Integer> fees = List.of(12000, 45000, 8000);
System.out.println("Wrong total: " + fees.stream().reduce(1, Integer::sum)); System.out.println("Right total: " + fees.stream().reduce(0, Integer::sum));
// empty result: orElse instead of get() int bigFee = fees.stream() .filter(f -> f > 100000) .max(Comparator.naturalOrder()) .orElse(0); System.out.println("Fee above 1 lakh: " + bigFee);
List<Integer> due = new ArrayList<>(fees.stream().filter(f -> f > 10000).toList()); due.add(5000); // late fine System.out.println("Due: " + due); }}Wrong total: 65001 Right total: 65000 Fee above 1 lakh: 0 Due: [12000, 45000, 5000]
What this code does
- The wrong identity gives 65001 with no error, which is why it slips into reports. The neutral identity for
+is 0. orElse(0)handles the empty result thatget()would crash on. WrappingtoList()innew ArrayList<>(...)gives a list thataddcan change.
reduce must also produce new values. Reducing into a StringBuilder or an ArrayList works on a sequential stream and breaks on a parallel one, so use collect, toList() or Collectors.joining for containers.
Mistake 3: reusing a stream or changing its result
A terminal operation closes the stream. Storing a Stream in a variable and calling count() and then max() on it throws IllegalStateException: stream has already been operated upon or closed.
Example 4 · Mistake: using one stream twice
import java.util.Comparator;import java.util.List;import java.util.stream.Stream;
public class ReuseStreamDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 94, 31, 88);
Stream<Integer> stream = marks.stream(); System.out.println("Count: " + stream.count()); try { System.out.println("Max: " + stream.max(Comparator.naturalOrder()).get()); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); }
// fix: keep the list, make a new stream for each question System.out.println("Count: " + marks.stream().count()); System.out.println("Max: " + marks.stream().max(Comparator.naturalOrder()).get()); }}Count: 4 Error: stream has already been operated upon or closed Count: 4 Max: 94
What this code does
count()is a terminal operation, so it closesstream. The second terminal call on the same object throwsIllegalStateException.- Store the source, not the stream.
marks.stream()is cheap, so creating one per question costs almost nothing.
Keep the source, such as the list, in a variable and call stream() again for each question.
The list from toList() is unmodifiable. Adding to it, removing from it or sorting it throws UnsupportedOperationException. Collect into an ArrayList when the code must keep changing the list.
Finish up
Mark complete & continue
Next: collect and the Collectors class