Skip to lesson

Build clean multi-step pipelines

A real pipeline chains five or more steps: parse, clean, filter, transform, sort, cut. The same steps in a different order can give the same answer with far less work, and the same logic written with named pieces can read like a plain sentence.

Ordering steps for speed

Each step does work for every element that reaches it, so the order of steps decides how much work is done in total, even when the result is the same.

Example 1 · Same result, different work: filter before map and sorted

StepOrderDemo.javaJava
import java.util.Comparator;import java.util.List;
public class StepOrderDemo {    static int mapCalls = 0;    static int compareCalls = 0;
    static String label(int amount) {        mapCalls++;                       // counting work for this demo only        return "Rs " + amount;    }
    static int byAmount(String a, String b) {        compareCalls++;        return Integer.compare(Integer.parseInt(a.substring(3)), Integer.parseInt(b.substring(3)));    }
    public static void main(String[] args) {        List<Integer> amounts = List.of(120, 4500, 80, 2600, 300, 9900, 40, 1500, 60, 700);
        List<String> slow = amounts.stream()                .map(StepOrderDemo::label)                .sorted(StepOrderDemo::byAmount)                .filter(s -> Integer.parseInt(s.substring(3)) >= 1000)                .toList();        System.out.println("map, sort, filter: " + slow);        System.out.println("  map calls " + mapCalls + ", comparisons " + compareCalls);
        mapCalls = 0;        compareCalls = 0;        List<String> fast = amounts.stream()                .filter(a -> a >= 1000)                .map(StepOrderDemo::label)                .sorted(StepOrderDemo::byAmount)                .toList();        System.out.println("filter, map, sort: " + fast);        System.out.println("  map calls " + mapCalls + ", comparisons " + compareCalls);    }}
Output
map, sort, filter: [Rs 1500, Rs 2600, Rs 4500, Rs 9900]
  map calls 10, comparisons 24
filter, map, sort: [Rs 1500, Rs 2600, Rs 4500, Rs 9900]
  map calls 4, comparisons 5

What this code does

  • Both pipelines give the same list. The first labels and sorts all 10 amounts and filters at the end; the second filters first, so only 4 amounts are labelled and sorted.
  • The counters are there only to measure the work. With a million orders the gap grows: sorting cost rises faster than the number of elements.

Four rules cover most pipelines:

  • Filter early. Every element a filter drops is one that later steps never touch. Put cheap filters, such as a status check, before expensive ones, such as parsing.
  • Map late, map small. Run costly map steps on the survivors only. If you need just one field, map to it early so later steps carry less.
  • Sort after filtering. sorted costs about n log n comparisons and holds every element in memory, so sort the smallest set you can.
  • Cut as soon as it is correct. limit right after sorted stops the later steps for everything past the top N.

Order of execution

Cheapest order of steps

Tap the steps in the order that does the least work.

List<Order> orders = loadOrders();
// goal: the ids of the three largest paid orders above 500
Reordering is safe only when the result stays the same. A filter that tests a value computed by map must stay after that map, and limit must stay after the sorted that decides what "first" means.

Pulling long lambdas into named methods and predicates

A pipeline should read like the business rule. .filter(o -> o.status().equals("DELIVERED") && o.amount() >= 500 && !o.city().isBlank()) makes the reader decode the rule. .filter(Order::isDelivered).filter(isBigOrder) states it.

Example 2 · From one long lambda to named pieces

NamedPiecesDemo.javaJava
import java.util.List;import java.util.function.Predicate;
record Order(String id, String city, String status, int amount) {    boolean isDelivered() {        return status.equals("DELIVERED");    }}
public class NamedPiecesDemo {    static final Predicate<Order> IS_BIG = o -> o.amount() >= 500;
    static String toLabel(Order o) {        return o.id() + " (" + o.city() + ")";    }
    public static void main(String[] args) {        List<Order> orders = List.of(                new Order("A1", "Pune", "DELIVERED", 1200),                new Order("A2", "Delhi", "CANCELLED", 900),                new Order("A3", "", "DELIVERED", 700),                new Order("A4", "Goa", "DELIVERED", 300),                new Order("A5", "Agra", "DELIVERED", 650));
        // before: the reader has to decode the rule        List<String> before = orders.stream()                .filter(o -> o.status().equals("DELIVERED") && o.amount() >= 500 && !o.city().isBlank())                .map(o -> o.id() + " (" + o.city() + ")")                .toList();
        // after: the pipeline reads like the rule        List<String> after = orders.stream()                .filter(Order::isDelivered)                .filter(IS_BIG)                .filter(o -> !o.city().isBlank())                .map(NamedPiecesDemo::toLabel)                .toList();
        System.out.println("Before: " + before);        System.out.println("After:  " + after);    }}
Output
Before: [A1 (Pune), A5 (Agra)]
After:  [A1 (Pune), A5 (Agra)]

What this code does

  • isDelivered lives on the record, IS_BIG is a named predicate constant, and toLabel is a static helper. Each can be reused and tested on its own.
  • Both versions give the same result. The second reads top to bottom as "delivered, big, has a city, label it".

Three tools do this. A method on the record, such as boolean isDelivered(), used as Order::isDelivered. A named predicate or function in a variable or constant, such as Predicate<Order> isBigOrder. A static helper method for a multi-line transformation, such as static Row toRow(Order o), used as Dashboard::toRow. Write one step per line and keep each lambda to one short expression. A lambda that needs braces and several statements is a method waiting to be named. Named pieces can also be tested on their own.

mapMulti (Java 16) as an alternative to flatMap

mapMulti (Java 16) is an intermediate step that hands each element and a sink to your lambda. Calling sink.accept(value) pushes one result downstream, so one element can produce none, one or many.

flatMap asks for a stream per element. When each element gives only zero, one or two results, building a tiny stream every time is clumsy and a little slow. mapMulti lets you push results instead.

Example 3 · mapMulti versus flatMap

MapMultiDemo.javaJava
import java.util.List;
record Order(String id, String status, List<String> items) {}
public class MapMultiDemo {    public static void main(String[] args) {        List<Order> orders = List.of(                new Order("O1", "PAID", List.of("Pen", "Notebook")),                new Order("O2", "CANCELLED", List.of("Bag")),                new Order("O3", "PAID", List.of("Lamp")));
        List<String> withFlatMap = orders.stream()                .filter(o -> !o.status().equals("CANCELLED"))                .flatMap(o -> o.items().stream().map(item -> o.id() + ":" + item))                .toList();        System.out.println("flatMap:  " + withFlatMap);
        List<String> withMapMulti = orders.stream()                .<String>mapMulti((o, sink) -> {                    if (o.status().equals("CANCELLED")) {                        return;                      // push nothing                    }                    for (String item : o.items()) {                        sink.accept(o.id() + ":" + item);   // push one result per item                    }                })                .toList();        System.out.println("mapMulti: " + withMapMulti);    }}
Output
flatMap:  [O1:Pen, O1:Notebook, O3:Lamp]
mapMulti: [O1:Pen, O1:Notebook, O3:Lamp]

What this code does

  • mapMulti gives you the element and a sink. Each sink.accept(...) pushes one result downstream; returning without calling it pushes nothing, so the cancelled order disappears.
  • The plain if and for replace both the filter and the inner stream of the flatMap version. <String> in front of mapMulti tells Java the result type.

Example 4 · Mistake: mapMulti without the type

MapMultiTypeDemo.javaJava
import java.util.List;
public class MapMultiTypeDemo {    public static void main(String[] args) {        List<String> lines = List.of("a,b", "c");        List<String> parts = lines.stream()                .mapMulti((line, sink) -> {                    for (String p : line.split(",")) {                        sink.accept(p);                    }                })                .toList();        System.out.println(parts);    }}
Sample compiler output
MapMultiTypeDemo.java:12: error: incompatible types: List<Object> cannot be converted to List<String>
                .toList();
                       ^
1 error

What this code does

  • Java cannot work out the result type from calls to sink.accept, so it picks Object. The stream becomes a Stream<Object>, and its List<Object> does not fit List<String>.
  • Write .<String>mapMulti(...) to name the result type. flatMap does not have this problem, because the stream you return carries its type.

The sink is an ordinary Consumer.

orders.stream().<String>mapMulti((o, sink) -> { for (String item : o.items()) sink.accept(item); }) does what flatMap(o -> o.items().stream()) does. It shines when results depend on a condition: skip cancelled orders and emit one row per item of the rest, in one step, with an ordinary if and for. Java cannot guess the result type from sink.accept(...), so write it in front: .<String>mapMulti(...). Without it the stream becomes a Stream<Object>. Prefer flatMap when you already have a stream or collection to return; prefer mapMulti when you would otherwise build small streams with Stream.of or Stream.empty().

Real-world use: raw order records to a dashboard list

A shop exports orders as text lines: id,city,status,amount. Some lines are blank or broken. The dashboard needs the 3 biggest delivered orders of the day, each as id city Rs amount.

  1. Clean the raw lines first: drop blank lines and lines that do not have four fields.
  2. Parse each remaining line into an Order record with a named parse method.
  3. Keep delivered orders with a method reference, Order::isDelivered.
  4. Sort by amount, highest first, then take the top 3 with limit.
  5. Map each order to the display text with a named toRow method, and collect with toList().

Example 5 · Real-world use: raw order lines to a dashboard

DashboardDemo.javaJava
import java.util.Comparator;import java.util.List;
record Order(String id, String city, String status, int amount) {    boolean isDelivered() {        return status.equals("DELIVERED");    }}
public class DashboardDemo {    static boolean hasFourFields(String line) {        return line.split(",").length == 4;    }
    static Order parse(String line) {        String[] f = line.split(",");        return new Order(f[0].trim(), f[1].trim(), f[2].trim(), Integer.parseInt(f[3].trim()));    }
    static String toRow(Order o) {        return String.format("%-4s %-8s Rs %,d", o.id(), o.city(), o.amount());    }
    public static void main(String[] args) {        List<String> export = List.of(                "A101,Pune,DELIVERED,1850",                "A102,Delhi,CANCELLED,4200",                "",                "A103,Chennai,DELIVERED,12999",                "A104,Goa,SHIPPED,700",                "broken line",                "A105, Jaipur ,DELIVERED, 5400",                "A106,Agra,DELIVERED,950");
        List<String> dashboard = export.stream()                .filter(line -> !line.isBlank())                .filter(DashboardDemo::hasFourFields)                .map(DashboardDemo::parse)                .filter(Order::isDelivered)                .sorted(Comparator.comparing(Order::amount).reversed())                .limit(3)                .map(DashboardDemo::toRow)                .toList();
        System.out.println("Top delivered orders");        dashboard.forEach(System.out::println);    }}
Output
Top delivered orders
A103 Chennai  Rs 12,999
A105 Jaipur   Rs 5,400
A101 Pune     Rs 1,850

What this code does

  • Cheap text checks run first, so broken and blank lines never reach parse. The status filter runs before sorted, so only the 4 delivered orders are sorted.
  • limit(3) sits right after sorted, so toRow formats only three orders. Every step is one line with one named idea, and %,d adds the thousands comma.

Next step

Check your understanding

12 quick questions