Build clean multi-step pipelines
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}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
filterdrops 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
mapsteps on the survivors only. If you need just one field, map to it early so later steps carry less. - Sort after filtering.
sortedcosts 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.
limitright aftersortedstops 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.
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
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); }}Before: [A1 (Pune), A5 (Agra)] After: [A1 (Pune), A5 (Agra)]
What this code does
isDeliveredlives on the record,IS_BIGis a named predicate constant, andtoLabelis 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
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); }}flatMap: [O1:Pen, O1:Notebook, O3:Lamp] mapMulti: [O1:Pen, O1:Notebook, O3:Lamp]
What this code does
mapMultigives you the element and asink. Eachsink.accept(...)pushes one result downstream; returning without calling it pushes nothing, so the cancelled order disappears.- The plain
ifandforreplace both thefilterand the inner stream of theflatMapversion.<String>in front ofmapMultitells Java the result type.
Example 4 · Mistake: mapMulti without the type
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); }}MapMultiTypeDemo.java:12: error: incompatible types: List<Object> cannot be converted to List<String>
.toList();
^
1 errorWhat this code does
- Java cannot work out the result type from calls to
sink.accept, so it picksObject. The stream becomes aStream<Object>, and itsList<Object>does not fitList<String>. - Write
.<String>mapMulti(...)to name the result type.flatMapdoes 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.
- Clean the raw lines first: drop blank lines and lines that do not have four fields.
- Parse each remaining line into an
Orderrecord with a namedparsemethod. - Keep delivered orders with a method reference,
Order::isDelivered. - Sort by amount, highest first, then take the top 3 with
limit. - Map each order to the display text with a named
toRowmethod, and collect withtoList().
Example 5 · Real-world use: raw order lines to a dashboard
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); }}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 beforesorted, so only the 4 delivered orders are sorted. limit(3)sits right aftersorted, sotoRowformats only three orders. Every step is one line with one named idea, and%,dadds the thousands comma.
Next step
Check your understanding
12 quick questions