Skip to lesson

Primitive and parallel streams: 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.

Number streams, generated streams and parallel streams each answer one kind of task. Practice is about recognising the task quickly: a total or average over numbers, a sequence where each value follows from the last, or a big calculation that might deserve several cores.

Number tasks: ranges, sums and averages

Most number exercises follow one shape: pick the source, turn it into a number stream, finish with one terminal operation. The source is a range (IntStream.rangeClosed(1, n)), an array (Arrays.stream(arr)) or a list of objects (list.stream().mapToInt(Student::marks)).

Example 1 · A class result card from number streams

ResultCardDemo.javaJava
import java.util.Arrays;import java.util.IntSummaryStatistics;import java.util.List;import java.util.stream.IntStream;
public class ResultCardDemo {    public static void main(String[] args) {        int[] marks = {78, 92, 35, 64, 88, 41, 70, 59};   // index 0 is roll 1
        IntSummaryStatistics stats = Arrays.stream(marks).summaryStatistics();        System.out.println("Students: " + stats.getCount());        System.out.println("Total:    " + stats.getSum());        System.out.println("Highest:  " + stats.getMax() + ", lowest: " + stats.getMin());        System.out.printf("Average:  %.2f%n", stats.getAverage());
        double avg = stats.getAverage();        List<Integer> aboveAverageRolls = IntStream.range(0, marks.length)                .filter(i -> marks[i] > avg)                .map(i -> i + 1)                .boxed()                .toList();        System.out.println("Rolls above average: " + aboveAverageRolls);
        long distinctions = Arrays.stream(marks).filter(m -> m >= 75).count();        System.out.println("Distinctions: " + distinctions + " of " + marks.length);    }}
Output
Students: 8
Total:    527
Highest:  92, lowest: 35
Average:  65.88
Rolls above average: [1, 2, 5, 7]
Distinctions: 3 of 8

What this code does

  • summaryStatistics() gives count, sum, min, max and average from one pass over the array, instead of five separate streams.
  • To report roll numbers, the pipeline streams the indexes with range(0, marks.length), compares each mark with the average and turns the index into a roll number with i + 1.

The finish is sum(), count(), average(), max(), min(), or summaryStatistics() when you need several of them in one pass. Remember the two traps: average(), max() and min() return an Optional, so use orElse when the data may be empty; and an int sum can overflow, so switch to mapToLong or asLongStream() for big totals.

Sequences with iterate and generate

If each value depends on the previous one, such as a reducing loan balance, Fibonacci numbers or a countdown, use Stream.iterate. When the state needs two numbers, carry them together in a small record or array.

Example 2 · An EMI schedule with iterate and a record

EmiScheduleDemo.javaJava
import java.util.stream.Stream;
record Month(int number, long balance) { }
public class EmiScheduleDemo {    public static void main(String[] args) {        long loan = 50_000;        long emi = 9_000;
        // each month: add 1% interest on the balance, then pay the EMI        Stream.iterate(new Month(0, loan),                        m -> m.balance() > 0,                        m -> new Month(m.number() + 1, m.balance() + m.balance() / 100 - emi))                .skip(1)                .forEach(m -> System.out.println("Month " + m.number() + ": balance " + m.balance()));
        Month last = Stream.iterate(new Month(0, loan),                        m -> m.balance() > 0,                        m -> new Month(m.number() + 1, m.balance() + m.balance() / 100 - emi))                .reduce((a, b) -> b)                .get();        long finalPayment = last.balance() + last.balance() / 100;        System.out.println("Month " + (last.number() + 1) + ": a last, smaller EMI of " + finalPayment + " clears the loan");    }}
Output
Month 1: balance 41500
Month 2: balance 32915
Month 3: balance 24244
Month 4: balance 15486
Month 5: balance 6640
Month 6: a last, smaller EMI of 6706 clears the loan

What this code does

  • The state needs two values, the month and the balance, so each element is a small record. The rule builds a new record; nothing outside the lambda changes.
  • The condition balance > 0 ends the stream before the balance would go below zero, so it is not infinite. skip(1) hides month 0, the starting loan, and reduce((a, b) -> b) keeps the last state, from which the final, smaller EMI is worked out.

If the stop is a condition, use the three-part iterate(seed, hasNext, next); if it is a count, use limit.

If each value is independent, such as random marks for test data, use Stream.generate with a seeded Random so every run gives the same data. Before running any generated stream, point to the step that stops it: limit, takeWhile, findFirst or the condition of iterate.

Fixing a parallel stream with a shared list

When a parallel stream gives a different answer on each run, look for something outside the lambdas that changes.

Example 3 · Fixing a parallel report and proving the fix

ParallelReportFixDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;import java.util.stream.IntStream;
record Sale(String city, int amount) { }
public class ParallelReportFixDemo {    static Map<String, Integer> report(List<Sale> sales, boolean parallel) {        // was: sales.parallelStream().forEach(s -> totals.merge(s.city(), s.amount(), Integer::sum));        return (parallel ? sales.parallelStream() : sales.stream())                .collect(Collectors.groupingBy(Sale::city, TreeMap::new, Collectors.summingInt(Sale::amount)));    }
    public static void main(String[] args) {        String[] cities = {"Chennai", "Delhi", "Mumbai", "Pune"};        List<Sale> sales = IntStream.range(0, 100_000)                .mapToObj(i -> new Sale(cities[i % 4], i % 1000))                .toList();
        Map<String, Integer> seq = report(sales, false);        Map<String, Integer> par = report(sales, true);
        System.out.println("Same result: " + seq.equals(par));        System.out.println(par);        System.out.println("Grand total: " + sales.parallelStream().mapToLong(Sale::amount).sum());    }}
Output
Same result: true
{Chennai=12450000, Delhi=12475000, Mumbai=12500000, Pune=12525000}
Grand total: 49950000

What this code does

  • The old version merged into one shared HashMap from many threads, which loses updates. groupingBy with summingInt gives each thread its own map and merges them safely.
  • The program proves the fix: the sequential and parallel maps are compared with equals before the result is trusted. TreeMap::new keeps the cities in A to Z order for a stable print.

The fix follows four steps:

  • Find the shared state: an outside ArrayList, HashMap, int[] counter or field changed in forEach, map or filter.
  • Replace it with a result the stream builds: toList(), count(), sum(), groupingBy(...).
  • Check every reduce: an associative function and a true identity (0 for sum, 1 for product).
  • Prove it: compute the sequential and parallel results and check that they are equal.

Loop, stream or parallel stream?

Ask three questions in order. Does the logic need a running value, an early exit with several variables, or a checked exception for the caller? Then a loop is clearer. Is it a filter, map and combine over a collection? Then a sequential stream reads best.

Is the data large, the work per element heavy, the source an array, ArrayList or range, and are there no blocking calls? Only then try a parallel stream, and keep it only if a warmed-up measurement shows a clear gain with the same result.

Finish up

Mark complete & continue

Next: Why Optional exists