Skip to main content

Programming languages · Intermediate · 22 min

Transform collections with Java streams and collectors

By Padding · Updated 18 Nov 2026
Eclipse Temurin JDK 25.0.5 · Linux or macOS

You will rewrite nested loops over a list of shop orders as Java 25 streams, group and total them with collectors, batch them with a stream gatherer, and finish with a printed sales report.

On this page

A stream in Java is a pipeline over the elements of a collection: you describe what to keep, how to change each element and how to combine the results, and the library runs those steps in one pass when you ask for an answer. A stream stores nothing itself and does not change the list it reads from. Code written this way often says what it computes in fewer lines than the loop it replaces, and the collectors in java.util.stream.Collectors turn the common jobs (count per group, total per group, split in two, build a map) into one call each.

In this tutorial you work on the orders of a small online shop that sells solar lamps, power banks and cables in four cities. You write the same answers twice, first as loops and then as streams, and the programs print both so you can see they agree. Then you run into the three mistakes that catch most people, try a stream gatherer from the API that became final in JDK 24, and put it all together in a sales report. The last step is honest about when a plain loop is the better choice.

Every program is a single .java file that you run with java File.java. Since JDK 22 the launcher also compiles the other source files in the same folder when the program uses them, so there is no build tool and no separate javac step.

Step 1 · Set up the orders

Check your Java version first. Everything here needs JDK 25, or at least 24 for the gatherer step:

Bash
java -version

Make a throwaway folder and describe the data with two records. A Line is one product on an order, and an Order holds its lines. Records give you a constructor, accessors such as order.city(), equals and toString for free:

Bash
mkdir -p ~/streams-demo
cd ~/streams-demo
cat > Line.java <<'JAVA'
public record Line(String product, int quantity, long unitCents) {
    public long totalCents() {
        return quantity * unitCents;
    }
}
JAVA
cat > Order.java <<'JAVA'
import java.util.List;

public record Order(String id, String city, String customer, List<Line> lines) {
    public long totalCents() {
        return lines.stream().mapToLong(Line::totalCents).sum();
    }
}
JAVA

Prices are whole numbers of cents in a long, never a double, because binary floating point cannot store most decimal amounts exactly and the error grows as you add. The same goes for naira and kobo, shillings and cents, or cedis and pesewas. Order.totalCents() is already a tiny stream: mapToLong turns each line into its total, and sum adds them up.

Now the shop's twelve orders, in the order they arrived, and a helper that prints cents as an amount:

Bash
cat > Shop.java <<'JAVA'
import java.util.List;

public final class Shop {
    private Shop() {}

    public static final List<Order> ORDERS = List.of(
        new Order("O-1001", "Lagos", "Ada", List.of(
            new Line("Solar lamp", 2, 2500), new Line("USB cable", 3, 500))),
        new Order("O-1002", "Nairobi", "Wanjiru", List.of(
            new Line("Power bank", 1, 4000))),
        new Order("O-1003", "Accra", "Kofi", List.of(
            new Line("Earbuds", 2, 3500), new Line("Phone charger", 1, 1200))),
        new Order("O-1004", "Lagos", "Tunde", List.of(
            new Line("Phone charger", 4, 1200))),
        new Order("O-1005", "Nairobi", "Wanjiru", List.of(
            new Line("Solar lamp", 3, 2500), new Line("Power bank", 1, 4000))),
        new Order("O-1006", "Lagos", "Ada", List.of(
            new Line("Earbuds", 1, 3500))),
        new Order("O-1007", "Kigali", "Amara", List.of(
            new Line("USB cable", 10, 500))),
        new Order("O-1008", "Accra", "Kofi", List.of(
            new Line("Solar lamp", 1, 2500))),
        new Order("O-1009", "Lagos", "Zola", List.of(
            new Line("Power bank", 2, 4000), new Line("Earbuds", 1, 3500))),
        new Order("O-1010", "Kigali", "Amara", List.of(
            new Line("Phone charger", 2, 1200), new Line("USB cable", 2, 500))),
        new Order("O-1011", "Nairobi", "Baraka", List.of(
            new Line("Earbuds", 3, 3500))),
        new Order("O-1012", "Lagos", "Tunde", List.of(
            new Line("Solar lamp", 2, 2500), new Line("Phone charger", 1, 1200)))
    );

    public static String money(long cents) {
        return String.format("%d.%02d", cents / 100, cents % 100);
    }
}
JAVA

Before any streams, write the kind of code they replace: two nested loops that count the lines and add up the money.

Bash
cat > CountOrders.java <<'JAVA'
public class CountOrders {
    public static void main(String[] args) {
        int lines = 0;
        long cents = 0;
        for (Order order : Shop.ORDERS) {
            for (Line line : order.lines()) {
                lines++;
                cents += line.totalCents();
            }
        }
        System.out.println(Shop.ORDERS.size() + " orders, " + lines + " lines, " + Shop.money(cents) + " in total");
    }
}
JAVA
java CountOrders.java

Check it worked

java -version prints something like openjdk version "25.0.5". ls ~/streams-demo shows CountOrders.java, Line.java, Order.java and Shop.java, and the program prints 12 orders, 18 lines, 776.00 in total. If you get cannot find symbol for Shop or Order, check that all four files are in the same folder and that you ran java from inside it.

Step 2 · Replace a loop with filter, sorted, limit and map

The question: which are the three biggest orders from Lagos? As a loop, that is a filter into a new list, a sort, and a counted loop to take the first three. As a stream, each of those jobs is one named operation:

Bash
cat > TopOrders.java <<'JAVA'
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class TopOrders {
    public static void main(String[] args) {
        // The loop version
        List<Order> lagos = new ArrayList<>();
        for (Order order : Shop.ORDERS) {
            if (order.city().equals("Lagos")) {
                lagos.add(order);
            }
        }
        lagos.sort((a, b) -> Long.compare(b.totalCents(), a.totalCents()));
        List<String> loopResult = new ArrayList<>();
        for (int i = 0; i < Math.min(3, lagos.size()); i++) {
            Order order = lagos.get(i);
            loopResult.add(order.id() + " " + Shop.money(order.totalCents()));
        }

        // The stream version
        List<String> streamResult = Shop.ORDERS.stream()
            .filter(order -> order.city().equals("Lagos"))
            .sorted(Comparator.comparingLong(Order::totalCents).reversed())
            .limit(3)
            .map(order -> order.id() + " " + Shop.money(order.totalCents()))
            .toList();

        System.out.println("loop:   " + loopResult);
        System.out.println("stream: " + streamResult);
        System.out.println("same: " + loopResult.equals(streamResult));
    }
}
JAVA
java TopOrders.java

Read the stream from top to bottom:

  • filter keeps the elements for which the lambda returns true.
  • sorted takes a Comparator. Comparator.comparingLong(Order::totalCents) sorts from small to large by a long key, and .reversed() flips it. For keys that are objects, such as a city name, use Comparator.comparing(Order::city), and chain .thenComparing(...) to break ties.
  • limit(3) stops after three elements.
  • map turns each order into a string.
  • toList() is the terminal operation. Nothing runs until a terminal operation asks for a result.

Stream.toList() returns a list you cannot change: calling add on it throws UnsupportedOperationException. If you need a list to add to later, collect with Collectors.toCollection(ArrayList::new) instead.

Check it worked

Both lines print [O-1009 115.00, O-1001 65.00, O-1012 62.00], followed by same: true. Change limit(3) to limit(10) and run it again: the stream line lists all five Lagos orders, not an error, because limit is a maximum (the loop still stops at three, so same becomes false).

Step 3 · Flatten nested lists with flatMap

Revenue per product means looking inside every order at every line. In loop form that is a loop inside a loop. In a stream, flatMap replaces each order with the stream of its lines, so the rest of the pipeline sees one flat stream of 18 lines. groupingBy then sorts the lines into buckets by product and summingLong adds up each bucket:

Bash
cat > ProductRevenue.java <<'JAVA'
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class ProductRevenue {
    public static void main(String[] args) {
        // The loop version: one loop per level of nesting
        Map<String, Long> loopTotals = new TreeMap<>();
        for (Order order : Shop.ORDERS) {
            for (Line line : order.lines()) {
                loopTotals.merge(line.product(), line.totalCents(), Long::sum);
            }
        }

        // The stream version: flatMap turns a stream of orders into a stream of lines
        Map<String, Long> streamTotals = Shop.ORDERS.stream()
            .flatMap(order -> order.lines().stream())
            .collect(Collectors.groupingBy(
                Line::product,
                TreeMap::new,
                Collectors.summingLong(Line::totalCents)));

        streamTotals.forEach((product, cents) ->
            System.out.println(product + ": " + Shop.money(cents)));
        System.out.println("same: " + loopTotals.equals(streamTotals));
    }
}
JAVA
java ProductRevenue.java

The three-argument groupingBy takes the key (Line::product), a factory for the map (TreeMap::new, which keeps keys in alphabetical order) and a downstream collector that decides what each bucket becomes. With the one-argument form you get a HashMap of lists, in no order you can rely on.

Check it worked

The program prints five products in alphabetical order, from Earbuds: 245.00 to USB cable: 75.00, then same: true. The five amounts add up to 776.00, the total from the first step.

Step 4 · Group, count and split with collectors

Collectors combine. The same groupingBy with a different downstream collector answers a different question, and partitioningBy is a groupingBy with only two keys, true and false:

Bash
cat > ByCity.java <<'JAVA'
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class ByCity {
    public static void main(String[] args) {
        Map<String, Long> ordersPerCity = Shop.ORDERS.stream()
            .collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.counting()));
        System.out.println("Orders per city: " + ordersPerCity);

        Map<String, Long> revenuePerCity = Shop.ORDERS.stream()
            .collect(Collectors.groupingBy(
                Order::city,
                TreeMap::new,
                Collectors.summingLong(Order::totalCents)));
        revenuePerCity.forEach((city, cents) ->
            System.out.println("  " + city + ": " + Shop.money(cents)));

        Map<Boolean, List<String>> bigAndSmall = Shop.ORDERS.stream()
            .collect(Collectors.partitioningBy(
                order -> order.totalCents() >= 7_000,
                Collectors.mapping(Order::id, Collectors.toList())));
        System.out.println("70.00 or more: " + bigAndSmall.get(true));
        System.out.println("under 70.00:   " + bigAndSmall.get(false));
    }
}
JAVA
java ByCity.java

counting() returns a Long, not an int, which is why the map is Map<String, Long>. mapping(Order::id, toList()) changes each element before it goes into its bucket, so the partition holds order IDs instead of whole orders. A partition always has both keys: if no order were 70.00 or more, get(true) would return an empty list, never null.

Check it worked

The first line is Orders per city: {Accra=2, Kigali=2, Lagos=5, Nairobi=3}. Lagos shows 325.00, the largest of the four city totals. Four orders are 70.00 or more (O-1003, O-1005, O-1009 and O-1011) and the other eight are under.

Step 5 · Build a map with toMap and a merge function

Collectors.toMap builds a map from a key and a value for each element. It assumes every key appears once. Customers who order twice break that assumption, so the first attempt below fails on purpose and the program prints the error. The second attempt passes a merge function, Long::sum, that says what to do when a key repeats:

Bash
cat > Customers.java <<'JAVA'
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Customers {
    public static void main(String[] args) {
        try {
            Map<String, Long> broken = Shop.ORDERS.stream()
                .collect(Collectors.toMap(Order::customer, Order::totalCents));
            System.out.println(broken);
        } catch (IllegalStateException e) {
            System.out.println("Without a merge function: " + e.getMessage());
        }

        Map<String, Long> spendPerCustomer = Shop.ORDERS.stream()
            .collect(Collectors.toMap(
                Order::customer,
                Order::totalCents,
                Long::sum,
                TreeMap::new));
        spendPerCustomer.forEach((customer, cents) ->
            System.out.println(customer + " spent " + Shop.money(cents)));
    }
}
JAVA
java Customers.java

The merge function receives the value already in the map and the new one, and returns the value to keep. Long::sum adds them. Math::max would keep each customer's largest order, and (first, second) -> first would keep the first one seen. The fourth argument, TreeMap::new, sorts the customers by name.

Check it worked

The first line is something like Without a merge function: Duplicate key Wanjiru (attempted merging values 4000 and 11500): Wanjiru's two orders were the first repeat in the list. Below it, seven customers are listed alphabetically, from Ada spent 100.00 to Zola spent 115.00, with Wanjiru spent 155.00 as the largest.

Step 6 · Avoid the three common stream mistakes

Run these on purpose so you recognise them later:

Bash
cat > Pitfalls.java <<'JAVA'
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Pitfalls {
    public static void main(String[] args) {
        // 1. A stream can be used once
        Stream<Order> lagos = Shop.ORDERS.stream().filter(o -> o.city().equals("Lagos"));
        System.out.println("Lagos orders: " + lagos.count());
        try {
            System.out.println("again: " + lagos.count());
        } catch (IllegalStateException e) {
            System.out.println("Second use: " + e.getMessage());
        }

        // 2. Side effects inside map may never run
        List<String> seen = new ArrayList<>();
        long counted = Shop.ORDERS.stream()
            .map(o -> {
                seen.add(o.id());
                return o;
            })
            .count();
        System.out.println("counted " + counted + ", but seen holds " + seen.size() + " ids");
        List<String> ids = Shop.ORDERS.stream().map(Order::id).toList();
        System.out.println("collected " + ids.size() + " ids the safe way");

        // 3. Parallel is not automatically faster
        int rounds = 20_000;
        long checksum = 0;
        long start = System.nanoTime();
        for (int i = 0; i < rounds; i++) {
            checksum += Shop.ORDERS.stream().mapToLong(Order::totalCents).sum();
        }
        long sequentialMs = (System.nanoTime() - start) / 1_000_000;
        start = System.nanoTime();
        for (int i = 0; i < rounds; i++) {
            checksum -= Shop.ORDERS.parallelStream().mapToLong(Order::totalCents).sum();
        }
        long parallelMs = (System.nanoTime() - start) / 1_000_000;
        System.out.println("sequential: " + sequentialMs + " ms, parallel: " + parallelMs + " ms, checksum " + checksum);
    }
}
JAVA
java Pitfalls.java

What each part shows:

  1. Streams are single-use. After count(), the stream in lagos is finished. To ask a second question, start a new stream from Shop.ORDERS. If you need the same filtered data several times, collect it into a list once and stream that list.
  2. Side effects in map are not guaranteed to run. The source list knows its size and map cannot change it, so count() returns 12 without running the lambda at all, and seen stays empty. The library is allowed to skip work like this. Keep lambdas in map and filter free of side effects, and get results out of a stream through its terminal operation (toList, collect, count), never by adding to an outside list. With a parallel stream, that outside ArrayList would also be written from several threads at once and lose items.
  3. Parallel streams cost more than they save on small data. Each parallel run splits the work across the common fork-join thread pool and joins the results, which takes far longer than adding twelve numbers. Parallel pays off only for large amounts of CPU-bound work per element, and only when you measure it. It is a poor fit inside a web server, where every request would share the same pool.

Check it worked

You see Lagos orders: 5, then Second use: stream has already been operated upon or closed, then counted 12, but seen holds 0 ids and collected 12 ids the safe way. The last line shows two times that depend on your machine. The parallel time is usually several times the sequential one, and the checksum is 0, which proves both versions computed the same totals.

Step 7 · Process orders in batches with a gatherer

Collectors shape the end of a pipeline. Gatherers, added as a final feature in JDK 24, are custom intermediate operations: steps in the middle that can keep state between elements. The built-in Gatherers.windowFixed(5) groups elements into lists of five, in order, which is what you want when you send orders to a courier or an API in fixed-size batches:

Bash
cat > Batches.java <<'JAVA'
import java.util.List;
import java.util.stream.Gatherers;

public class Batches {
    public static void main(String[] args) {
        List<String> batches = Shop.ORDERS.stream()
            .gather(Gatherers.windowFixed(5))
            .map(batch -> batch.getFirst().id() + " to " + batch.getLast().id()
                + ": " + batch.size() + " orders, "
                + Shop.money(batch.stream().mapToLong(Order::totalCents).sum()))
            .toList();
        batches.forEach(System.out::println);
    }
}
JAVA
java Batches.java

After .gather(Gatherers.windowFixed(5)), the stream holds List<Order> elements instead of orders, so map receives a whole batch. Before gatherers, batching meant a loop with a counter and a list you cleared by hand. The same class has windowSliding, fold, scan and mapConcurrent, and you can write your own by implementing the Gatherer interface.

Check it worked

The program prints three lines: O-1001 to O-1005: 5 orders, 350.00, O-1006 to O-1010: 5 orders, 259.00 and O-1011 to O-1012: 2 orders, 167.00. The last batch is short because twelve does not divide by five, and windowFixed keeps the remainder rather than dropping it. On JDK 21 or older, the program fails with cannot find symbol for Gatherers.

Step 8 · Print the sales report

Now combine the pieces. summaryStatistics() gets the count, sum, largest value and average in one pass, and Map.Entry.comparingByValue() finds the biggest entry of a map you built with a collector. The running total at the end is a plain loop on purpose:

Bash
cat > SalesReport.java <<'JAVA'
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class SalesReport {
    public static void main(String[] args) {
        List<Order> orders = Shop.ORDERS;

        LongSummaryStatistics stats = orders.stream()
            .mapToLong(Order::totalCents)
            .summaryStatistics();

        Map<String, Long> revenuePerCity = orders.stream()
            .collect(Collectors.groupingBy(
                Order::city, TreeMap::new, Collectors.summingLong(Order::totalCents)));
        Map<String, Long> ordersPerCity = orders.stream()
            .collect(Collectors.groupingBy(Order::city, Collectors.counting()));
        Map.Entry<String, Long> bestCity = revenuePerCity.entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .orElseThrow();

        List<String> topProducts = orders.stream()
            .flatMap(order -> order.lines().stream())
            .collect(Collectors.groupingBy(Line::product, Collectors.summingLong(Line::totalCents)))
            .entrySet().stream()
            .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
            .limit(3)
            .map(e -> e.getKey() + " " + Shop.money(e.getValue()))
            .toList();

        Map.Entry<String, Long> bestCustomer = orders.stream()
            .collect(Collectors.toMap(Order::customer, Order::totalCents, Long::sum))
            .entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .orElseThrow();

        Map<Boolean, Long> bigOrders = orders.stream()
            .collect(Collectors.partitioningBy(o -> o.totalCents() >= 7_000, Collectors.counting()));

        // A plain loop: running state and an early exit
        long runningCents = 0;
        String passedTarget = "never";
        for (Order order : orders) {
            runningCents += order.totalCents();
            if (runningCents >= 30_000) {
                passedTarget = order.id();
                break;
            }
        }

        System.out.println("Sales report: " + stats.getCount() + " orders");
        System.out.println("Revenue:        " + Shop.money(stats.getSum()));
        System.out.println("Average order:  " + Shop.money(Math.round(stats.getAverage())));
        System.out.println("Largest order:  " + Shop.money(stats.getMax()));
        System.out.println("Best city:      " + bestCity.getKey() + ", " + Shop.money(bestCity.getValue())
            + " from " + ordersPerCity.get(bestCity.getKey()) + " orders");
        System.out.println("Top products:");
        for (int i = 0; i < topProducts.size(); i++) {
            System.out.println("  " + (i + 1) + ". " + topProducts.get(i));
        }
        System.out.println("Best customer:  " + bestCustomer.getKey() + ", " + Shop.money(bestCustomer.getValue()));
        System.out.println("Orders of 70.00 or more: " + bigOrders.get(true) + " of " + stats.getCount());
        System.out.println("Revenue passed 300.00 at: " + passedTarget);
    }
}
JAVA
java SalesReport.java

Map.Entry.<String, Long>comparingByValue() needs the type arguments written out because .reversed() follows it, and Java cannot work out the types of a generic method call that is itself the target of another call. Without them the compiler cannot infer the types and the line does not compile.

When a plain loop reads better

The running total is a loop because it carries state from one order to the next and stops early once the target is reached. A stream can do it, but only with tricks (a mutable holder in a lambda, or a gatherer written for the purpose) that hide what is going on. Reach for a loop when:

  • each step depends on the result of the step before, or you need to stop as soon as a condition holds;
  • you need the index, or to look at the previous or next element;
  • the body calls methods that throw checked exceptions, such as file or network I/O, which the standard functional interfaces behind map and filter do not let a lambda throw;
  • you update several unrelated totals in one pass and a stream would need one pipeline for each.

Streams earn their place when the job is "keep these, change those, combine the rest", as in every other section of this report.

Check it worked

The report starts with Sales report: 12 orders and Revenue: 776.00, the same total the nested loops printed in the first step. It names Lagos as the best city with 325.00 from 5 orders, lists Earbuds, Solar lamp and Power bank as the top three products, names Wanjiru as the best customer and ends with Revenue passed 300.00 at: O-1005.

Step 9 · Clean up

Leave the folder first, then remove only what this tutorial made. The JDK stays installed:

Bash
cd ~
rm -rf ~/streams-demo

Check it worked

ls ~/streams-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.