Patterncore
Collection pipeline
Also called pipeline of collection operations, method chain, stream pipeline, LINQ method chain, iterator chain, map filter reduce, chain of operations.
Write a computation over a collection as a sequence of operations such as filter, map, sort and reduce. Each operation takes a collection from the step before and gives a collection to the next step.
- Family
- architectural
- Intent
- Organize a computation over a collection as a sequence of small operations that each take a collection and give a new collection to the next operation.
- Also called
- Pipes and Filters (the general form)
Intent
Write a computation over a collection as a sequence of small, named operations. Fowler defines the pattern: "A collection pipeline lays out a sequence of operations that pass a collection of items between them. Each operation takes a collection as an input and emits another collection (except the last operation, which may be a terminal that emits a single value)"1. The common operations are filter, map, sort, flat map, group by and reduce.
The pattern is the reason that most languages now have methods such as filter and map on their collections or streams. This page explains the pattern, the difference between eager and lazy pipelines, and when a loop is the better choice.
Problem
A blog has articles. Each article has a title, a number of words and a list of tags. A program must find the titles of the two longest articles with the tag nosql, and the total number of words in all the articles with that tag. A first version uses one loop:
articles = [
("Intro to NoSQL", 1200, ["nosql", "databases"]),
("Event sourcing", 800, ["architecture"]),
("Graph stores", 1500, ["nosql", "graphs"]),
("Refactoring loops", 600, ["refactoring"]),
("Key-value stores", 900, ["nosql"]),
]
# One loop does three jobs: it selects, it sums and it collects.
selected = []
total = 0
for title, words, tags in articles:
if "nosql" in tags:
selected.append((words, title))
total += words
selected.sort(reverse=True)
top = []
for words, title in selected:
if len(top) == 2:
break
top.append(title)
print(top, total)
['Graph stores', 'Intro to NoSQL'] 3600
The result is correct, but the reader must find the parts of the computation in the body of the loop. The if is the selection. The append and the += are two different results. The second loop with break is a limit. Each new question about the articles adds a variable and more lines to the loop, and the jobs mix more. See Loops.
Solution
Give each job its own operation and connect the operations. Each operation gets a collection and gives a new collection. The last operation can give one value.
from functools import reduce
articles = [
("Intro to NoSQL", 1200, ["nosql", "databases"]),
("Event sourcing", 800, ["architecture"]),
("Graph stores", 1500, ["nosql", "graphs"]),
("Refactoring loops", 600, ["refactoring"]),
("Key-value stores", 900, ["nosql"]),
]
def words(article):
return article[1]
def title(article):
return article[0]
# filter: keep the NoSQL articles.
nosql = list(filter(lambda a: "nosql" in a[2], articles))
# sort, slice, map: the titles of the two longest ones.
top = list(map(title, sorted(nosql, key=words, reverse=True)[:2]))
# map, reduce: the total number of words.
total = reduce(lambda acc, n: acc + n, map(words, nosql), 0)
print(top, total)
['Graph stores', 'Intro to NoSQL'] 3600
Each line now says one thing: keep these articles, take the two longest titles, add up the words. A new question is a new pipeline, not a change to a shared loop.
The parts of the pattern:
- The source. A list, an array, a set, the lines of a file, the rows of a query or a generator of values.
- The operations. Each one is small and does one thing. Most operations take a function as a parameter: the test for
filter, the change formap, the key forsortandgroup by. See Higher-order function. - The composition. Fowler lists three forms1. A Unix shell connects processes with
|. An object-oriented language chains methods, soarticles.filter(...).map(...)reads from left to right. A functional language nests function calls,map(f, filter(p, xs)), which reads from the inside out, or uses an operator such as the Clojure->>macro to make the nested calls into a line. - The terminal. The last step makes a list, a set, a map, a number or an effect such as printing. Java calls it the terminal operation: "A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel); followed by zero or more intermediate operations such as Stream.filter or Stream.map; and a terminal operation such as Stream.forEach or Stream.reduce"2.
The common operations have different names in different languages. Fowler's article has a catalog of them1:
| Operation | Does | Other names |
|---|---|---|
| map | applies a function to each item | collect (Smalltalk, Ruby), Select (C#), transform (C++) |
| filter | keeps the items that pass a test | select (Ruby), Where (C#), grep (shell) |
| reject | drops the items that pass a test | filterNot (Kotlin, Scala), grep -v (shell) |
| flat map | maps each item to a collection and joins the results | mapcat (Clojure), SelectMany (C#), flat_map (Rust) |
| reduce | combines the items into one value | fold, inject (Smalltalk, Ruby), Aggregate (C#) |
| group by | puts the items into groups by a key | groupingBy (Java), GroupBy (C#), Object.groupBy (JavaScript) |
| sort | gives the items in order by a comparator or a key | sorted (Java, Python), OrderBy (C#) |
| take, drop | keeps or drops the first n items | limit and skip (Java), head and tail (shell) |
| distinct | drops repeated items | uniq (shell, Ruby), Distinct (C#) |
Eager and lazy pipelines. An eager pipeline makes a full collection after each step. A lazy pipeline sends the items through all the steps one at a time, and does no work until the terminal step asks for items. Java says of its intermediate operations: "They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering"2. Kotlin gives the difference: for a collection, "each processing step completes and returns its result – an intermediate collection", but "multistep processing of sequences is executed lazily when possible: actual computing happens only when the result of the whole processing chain is requested"3. A lazy pipeline can stop early. When the last step needs only the first match, the earlier steps run only for the items before it. Each example file counts the calls of a slow score function in the two forms, and gives 5 calls for the eager form and 1 call for the lazy form, except C++.
Example
Each example file runs the same pipelines on the same five articles: the two longest NoSQL titles, the total words, the number of articles for each tag, and the eager and lazy forms of "the first score over 1000".
| Language | Operations | Lazy form |
|---|---|---|
| Python | filter, map, sorted, functools.reduce, collections.Counter, itertools.chain |
generator expressions and itertools.islice |
| JavaScript | array methods filter, map, toSorted, flatMap, reduce, Object.groupBy |
iterator helpers on values() |
| Java | Stream methods and Collectors.groupingBy |
every stream; toList in the middle makes it eager |
| C# | LINQ Where, Select, OrderByDescending, SelectMany, GroupBy, Aggregate |
every LINQ chain; ToList in the middle makes it eager |
| Go | the slices package and small Map, Filter and Take functions over iter.Seq |
the iterator functions |
| Rust | iterator adapters filter, map, take, flat_map, fold |
every iterator chain; collect in the middle makes it eager |
| C++ | range algorithms copy_if, sort, transform, and std::accumulate |
views transform, filter, take, join |
| C | loops over arrays and qsort |
one loop that does all the steps and stops with break |
The C++ lazy form gives 4 calls, not 1. A filter view calls the transform before it once to test an item and once more to give the item. The loop also moves the filter to the next match before take(1) stops it. A lazy pipeline does not promise one call for each item, so a slow or impure function in a pipeline needs care.
from collections import Counter
from functools import reduce
from itertools import chain, islice
articles = [
("Intro to NoSQL", 1200, ["nosql", "databases"]),
("Event sourcing", 800, ["architecture"]),
("Graph stores", 1500, ["nosql", "graphs"]),
("Refactoring loops", 600, ["refactoring"]),
("Key-value stores", 900, ["nosql"]),
]
# filter, sort, slice and map: the titles of the two longest NoSQL articles.
nosql = [a for a in articles if "nosql" in a[2]]
print([t for t, _, _ in sorted(nosql, key=lambda a: a[1], reverse=True)[:2]])
# map and reduce: the total number of words in the NoSQL articles.
print(reduce(lambda acc, n: acc + n, map(lambda a: a[1], nosql), 0))
# flat map and group by: the number of articles for each tag.
counts = Counter(chain.from_iterable(tags for _, _, tags in articles))
print(sorted(counts.items()))
calls = 0
def score(article):
global calls
calls += 1
return article[1]
# An eager pipeline makes a full list at each step, so it computes every score.
eager = [s for s in [score(a) for a in articles] if s > 1000][:1]
print("eager", eager, calls)
# A lazy pipeline of iterators stops after the first item that passes.
calls = 0
lazy = list(islice((s for s in map(score, articles) if s > 1000), 1))
print("lazy", lazy, calls)
['Graph stores', 'Intro to NoSQL']
3600
[('architecture', 1), ('databases', 1), ('graphs', 1), ('nosql', 3), ('refactoring', 1)]
eager [1200] 5
lazy [1200] 1
- Verdict: native. Python has map, filter, sorted and functools.reduce as functions, so a pipeline nests calls or uses comprehensions for the steps. collections.Counter does the group by and count, and itertools.chain.from_iterable does the flat map. A list comprehension is eager and computes all 5 scores. A generator expression over map is lazy, and itertools.islice stops it after the first match, so score runs once.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <ranges>
#include <string>
#include <vector>
struct Article {
std::string title;
int words;
std::vector<std::string> tags;
};
int main() {
const std::vector<Article> articles{
{"Intro to NoSQL", 1200, {"nosql", "databases"}},
{"Event sourcing", 800, {"architecture"}},
{"Graph stores", 1500, {"nosql", "graphs"}},
{"Refactoring loops", 600, {"refactoring"}},
{"Key-value stores", 900, {"nosql"}},
};
// copy_if and sort are eager algorithms. take and transform are lazy views.
std::vector<Article> nosql;
std::ranges::copy_if(articles, std::back_inserter(nosql),
[](const Article& a) { return std::ranges::find(a.tags, "nosql") != a.tags.end(); });
std::ranges::sort(nosql, std::ranges::greater{}, &Article::words);
const char* sep = "";
for (const auto& t : nosql | std::views::take(2) | std::views::transform(&Article::title)) {
std::cout << sep << t;
sep = ", ";
}
std::cout << '\n';
// transform and accumulate are map and reduce.
auto words = nosql | std::views::transform(&Article::words);
std::cout << std::accumulate(words.begin(), words.end(), 0) << '\n';
// transform and join are a flat map. A loop fills the map of counts.
std::map<std::string, int> counts;
for (const auto& t : articles | std::views::transform(&Article::tags) | std::views::join) {
++counts[t];
}
sep = "";
for (const auto& [tag, c] : counts) {
std::cout << sep << tag << '=' << c;
sep = " ";
}
std::cout << '\n';
int calls = 0;
auto score = [&calls](const Article& a) {
++calls;
return a.words;
};
auto longer = [](int s) { return s > 1000; };
// A vector between the steps makes the pipeline eager: every score is computed.
std::vector<int> all;
std::ranges::transform(articles, std::back_inserter(all), score);
for (int s : all | std::views::filter(longer) | std::views::take(1)) {
std::cout << "eager " << s << ' ' << calls << '\n';
}
// Views are lazy, but the count is 4, not 1. filter calls the transform once to
// test an item and again to read it. The loop also moves the filter to the next
// match (800, then 1500) before take(1) ends the loop.
calls = 0;
for (int s : articles | std::views::transform(score) | std::views::filter(longer) | std::views::take(1)) {
std::cout << "lazy " << s << ' ';
}
std::cout << calls << '\n';
}
Graph stores, Intro to NoSQL
3600
architecture=1 databases=1 graphs=1 nosql=3 refactoring=1
eager 1200 5
lazy 1200 4
- Verdict: stdlib. The range algorithms copy_if, sort and transform are eager. The views take, transform, filter and join are lazy and join with |. The eager form computes all 5 scores into a vector. The lazy form gives 4 calls, not 1: filter calls the transform once to test an item and again to read it, and the loop moves the filter to the next match (800, then 1500) before take(1) ends the loop.
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
record Article(String title, int words, List<String> tags) {}
static int calls = 0;
static int score(Article a) {
calls++;
return a.words();
}
public static void main(String[] args) {
List<Article> articles = List.of(
new Article("Intro to NoSQL", 1200, List.of("nosql", "databases")),
new Article("Event sourcing", 800, List.of("architecture")),
new Article("Graph stores", 1500, List.of("nosql", "graphs")),
new Article("Refactoring loops", 600, List.of("refactoring")),
new Article("Key-value stores", 900, List.of("nosql")));
// A stream pipeline: a source, intermediate operations and a terminal operation.
List<Article> nosql = articles.stream().filter(a -> a.tags().contains("nosql")).toList();
System.out.println(nosql.stream()
.sorted(Comparator.comparingInt(Article::words).reversed())
.limit(2)
.map(Article::title)
.toList());
// map and reduce.
System.out.println(nosql.stream().map(Article::words).reduce(0, Integer::sum));
// flatMap and groupingBy: the number of articles for each tag.
Map<String, Long> counts = articles.stream()
.flatMap(a -> a.tags().stream())
.collect(Collectors.groupingBy(t -> t, TreeMap::new, Collectors.counting()));
System.out.println(counts);
// A list between the steps makes the pipeline eager: every score is computed.
List<Integer> all = articles.stream().map(Main::score).toList();
List<Integer> eager = all.stream().filter(s -> s > 1000).limit(1).toList();
System.out.println("eager " + eager + " " + calls);
// One stream is lazy: each item goes through all the steps, and limit stops the work.
calls = 0;
List<Integer> lazy = articles.stream().map(Main::score).filter(s -> s > 1000).limit(1).toList();
System.out.println("lazy " + lazy + " " + calls);
}
}
[Graph stores, Intro to NoSQL]
3600
{architecture=1, databases=1, graphs=1, nosql=3, refactoring=1}
eager [1200] 5
lazy [1200] 1
- Verdict: stdlib. A stream pipeline has a source, intermediate operations such as filter, sorted, map and flatMap, and a terminal operation such as toList, reduce or collect. Collectors.groupingBy with a TreeMap and Collectors.counting gives the counts in key order. A toList between map and filter makes the pipeline eager, so score runs 5 times. One stream is lazy, and limit(1) stops it after the first match.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *title;
int words;
const char *tags[2];
} Article;
static int has_tag(const Article *a, const char *tag) {
for (int i = 0; i < 2 && a->tags[i] != NULL; i++) {
if (strcmp(a->tags[i], tag) == 0) {
return 1;
}
}
return 0;
}
static int by_words_desc(const void *x, const void *y) {
const Article *a = x;
const Article *b = y;
return (b->words > a->words) - (b->words < a->words);
}
static int calls = 0;
static int score(const Article *a) {
calls++;
return a->words;
}
int main(void) {
const Article articles[] = {
{"Intro to NoSQL", 1200, {"nosql", "databases"}},
{"Event sourcing", 800, {"architecture", NULL}},
{"Graph stores", 1500, {"nosql", "graphs"}},
{"Refactoring loops", 600, {"refactoring", NULL}},
{"Key-value stores", 900, {"nosql", NULL}},
};
const int n = (int)(sizeof articles / sizeof articles[0]);
// C has no pipeline operations. Each step is a loop over an array, or qsort.
Article nosql[5];
int count = 0;
for (int i = 0; i < n; i++) {
if (has_tag(&articles[i], "nosql")) {
nosql[count++] = articles[i];
}
}
qsort(nosql, (size_t)count, sizeof nosql[0], by_words_desc);
printf("%s, %s\n", nosql[0].title, nosql[1].title);
int total = 0;
for (int i = 0; i < count; i++) {
total += nosql[i].words;
}
printf("%d\n", total);
// Eager: one loop computes every score into an array, a second loop filters it.
int all[5];
for (int i = 0; i < n; i++) {
all[i] = score(&articles[i]);
}
int first = -1;
for (int i = 0; i < n && first < 0; i++) {
if (all[i] > 1000) {
first = all[i];
}
}
printf("eager %d %d\n", first, calls);
// Fused: one loop does map, filter and take, and stops at the first match.
calls = 0;
first = -1;
for (int i = 0; i < n; i++) {
int s = score(&articles[i]);
if (s > 1000) {
first = s;
break;
}
}
printf("lazy %d %d\n", first, calls);
return 0;
}
Graph stores, Intro to NoSQL
3600
eager 1200 5
lazy 1200 1
- Verdict: idiom. C has no pipeline operations and no closures. Each step is a loop over an array, and qsort does the sort with a comparison function. The eager form computes all 5 scores into an array and then filters it. The fused form does map, filter and take in one loop and stops with break, so score runs once. This fused loop is the work that a lazy pipeline does for the program.
using System;
using System.Collections.Generic;
using System.Linq;
var articles = new[]
{
(Title: "Intro to NoSQL", Words: 1200, Tags: new[] { "nosql", "databases" }),
(Title: "Event sourcing", Words: 800, Tags: new[] { "architecture" }),
(Title: "Graph stores", Words: 1500, Tags: new[] { "nosql", "graphs" }),
(Title: "Refactoring loops", Words: 600, Tags: new[] { "refactoring" }),
(Title: "Key-value stores", Words: 900, Tags: new[] { "nosql" }),
};
// Where, OrderByDescending, Take and Select: a LINQ method chain.
var nosql = articles.Where(a => a.Tags.Contains("nosql")).ToList();
Console.WriteLine(string.Join(", ", nosql.OrderByDescending(a => a.Words).Take(2).Select(a => a.Title)));
// Select and Aggregate are map and reduce.
Console.WriteLine(nosql.Select(a => a.Words).Aggregate(0, (acc, n) => acc + n));
// SelectMany and GroupBy: the number of articles for each tag.
var counts = articles
.SelectMany(a => a.Tags)
.GroupBy(t => t)
.OrderBy(g => g.Key, StringComparer.Ordinal)
.Select(g => $"{g.Key}={g.Count()}");
Console.WriteLine(string.Join(" ", counts));
int calls = 0;
int Score((string Title, int Words, string[] Tags) a)
{
calls++;
return a.Words;
}
// ToList in the middle makes the pipeline eager: every score is computed.
var eager = articles.Select(Score).ToList().Where(s => s > 1000).Take(1).ToList();
Console.WriteLine($"eager {string.Join(",", eager)} {calls}");
// A LINQ chain is deferred: Take(1) stops the work after the first match.
calls = 0;
var lazy = articles.Select(Score).Where(s => s > 1000).Take(1).ToList();
Console.WriteLine($"lazy {string.Join(",", lazy)} {calls}");
Graph stores, Intro to NoSQL
3600
architecture=1 databases=1 graphs=1 nosql=3 refactoring=1
eager 1200 5
lazy 1200 1
- Verdict: stdlib. LINQ methods such as Where, OrderByDescending, Take, Select, SelectMany, GroupBy and Aggregate form the chain. A LINQ chain is deferred, so it runs only when ToList or string.Join reads it. ToList between Select and Where makes the pipeline eager, so Score runs 5 times. The chain without it stops after the first match, so Score runs once.
const articles = [
{ title: "Intro to NoSQL", words: 1200, tags: ["nosql", "databases"] },
{ title: "Event sourcing", words: 800, tags: ["architecture"] },
{ title: "Graph stores", words: 1500, tags: ["nosql", "graphs"] },
{ title: "Refactoring loops", words: 600, tags: ["refactoring"] },
{ title: "Key-value stores", words: 900, tags: ["nosql"] },
];
// filter, sort, slice and map: each array method returns a new array.
const nosql = articles.filter((a) => a.tags.includes("nosql"));
console.log(nosql.toSorted((a, b) => b.words - a.words).slice(0, 2).map((a) => a.title));
// map and reduce.
console.log(nosql.map((a) => a.words).reduce((acc, n) => acc + n, 0));
// flatMap and Object.groupBy: the number of articles for each tag.
const groups = Object.groupBy(articles.flatMap((a) => a.tags), (t) => t);
console.log(Object.keys(groups).sort().map((t) => `${t}=${groups[t].length}`).join(" "));
let calls = 0;
const score = (a) => {
calls++;
return a.words;
};
// Array methods are eager: map computes every score before filter runs.
const eager = articles.map(score).filter((s) => s > 1000).slice(0, 1);
console.log("eager", eager, calls);
// Iterator helpers are lazy: take(1) stops the work after the first match.
calls = 0;
const lazy = articles.values().map(score).filter((s) => s > 1000).take(1).toArray();
console.log("lazy", lazy, calls);
[ 'Graph stores', 'Intro to NoSQL' ]
3600
architecture=1 databases=1 graphs=1 nosql=3 refactoring=1
eager [ 1200 ] 5
lazy [ 1200 ] 1
- Verdict: native. The array methods filter, map, toSorted, slice, flatMap and reduce chain from left to right, and each one returns a new array, so the chain is eager and computes all 5 scores. Object.groupBy groups the tags. The iterator helpers on articles.values() are lazy, and take(1) stops the work after the first match, so score runs once.
package main
import (
"fmt"
"iter"
"slices"
)
type article struct {
title string
words int
tags []string
}
// Map, Filter and Take are lazy steps. Each one wraps an iterator in a new iterator.
func Map[T, U any](seq iter.Seq[T], f func(T) U) iter.Seq[U] {
return func(yield func(U) bool) {
for v := range seq {
if !yield(f(v)) {
return
}
}
}
}
func Filter[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for v := range seq {
if keep(v) && !yield(v) {
return
}
}
}
}
func Take[T any](seq iter.Seq[T], n int) iter.Seq[T] {
return func(yield func(T) bool) {
if n <= 0 {
return
}
i := 0
for v := range seq {
if !yield(v) {
return
}
i++
if i == n {
return
}
}
}
}
func main() {
articles := []article{
{"Intro to NoSQL", 1200, []string{"nosql", "databases"}},
{"Event sourcing", 800, []string{"architecture"}},
{"Graph stores", 1500, []string{"nosql", "graphs"}},
{"Refactoring loops", 600, []string{"refactoring"}},
{"Key-value stores", 900, []string{"nosql"}},
}
// filter, sort, take and map, built from the steps above and the slices package.
isNoSQL := func(a article) bool { return slices.Contains(a.tags, "nosql") }
byWordsDesc := func(a, b article) int { return b.words - a.words }
nosql := slices.Collect(Filter(slices.Values(articles), isNoSQL))
sorted := slices.SortedFunc(slices.Values(nosql), byWordsDesc)
titles := slices.Collect(Map(Take(slices.Values(sorted), 2), func(a article) string { return a.title }))
fmt.Printf("%q\n", titles)
// map and reduce: a range loop over the iterator does the reduce.
total := 0
for w := range Map(slices.Values(nosql), func(a article) int { return a.words }) {
total += w
}
fmt.Println(total)
// flat map and group by: nested loops fill a map. Println prints the keys in order.
counts := map[string]int{}
for _, a := range articles {
for _, t := range a.tags {
counts[t]++
}
}
fmt.Println(counts)
calls := 0
score := func(a article) int {
calls++
return a.words
}
long := func(s int) bool { return s > 1000 }
// A slice between the steps makes the pipeline eager: every score is computed.
all := slices.Collect(Map(slices.Values(articles), score))
eager := slices.Collect(Take(Filter(slices.Values(all), long), 1))
fmt.Println("eager", eager, calls)
// Iterators make the pipeline lazy: Take stops the work after the first match.
calls = 0
lazy := slices.Collect(Take(Filter(Map(slices.Values(articles), score), long), 1))
fmt.Println("lazy", lazy, calls)
}
["Graph stores" "Intro to NoSQL"]
3600
map[architecture:1 databases:1 graphs:1 nosql:3 refactoring:1]
eager [1200] 5
lazy [1200] 1
- Verdict: idiom. The Go standard library has iterators (iter.Seq) and functions such as slices.Values, slices.Collect and slices.SortedFunc, but no map or filter. The program writes Map, Filter and Take as functions that wrap one iterator in another. A slice between the steps makes the pipeline eager, so score runs 5 times. The iterator chain is lazy, and Take stops it after the first match.
use std::cell::Cell;
use std::collections::BTreeMap;
struct Article {
title: &'static str,
words: u32,
tags: &'static [&'static str],
}
fn main() {
let articles = [
Article { title: "Intro to NoSQL", words: 1200, tags: &["nosql", "databases"] },
Article { title: "Event sourcing", words: 800, tags: &["architecture"] },
Article { title: "Graph stores", words: 1500, tags: &["nosql", "graphs"] },
Article { title: "Refactoring loops", words: 600, tags: &["refactoring"] },
Article { title: "Key-value stores", words: 900, tags: &["nosql"] },
];
// filter and collect, then sort, take and map.
let mut nosql: Vec<&Article> = articles.iter().filter(|a| a.tags.contains(&"nosql")).collect();
nosql.sort_by(|a, b| b.words.cmp(&a.words));
let top: Vec<&str> = nosql.iter().take(2).map(|a| a.title).collect();
println!("{:?}", top);
// map and fold: fold is the reduce of Rust iterators.
let total = nosql.iter().map(|a| a.words).fold(0, |acc, n| acc + n);
println!("{}", total);
// flat_map and a fold into a map: the number of articles for each tag.
let counts = articles.iter().flat_map(|a| a.tags.iter()).fold(BTreeMap::new(), |mut m, t| {
*m.entry(*t).or_insert(0) += 1;
m
});
println!("{:?}", counts);
let calls = Cell::new(0);
let score = |a: &Article| {
calls.set(calls.get() + 1);
a.words
};
// A Vec between the steps makes the pipeline eager: every score is computed.
let all: Vec<u32> = articles.iter().map(score).collect();
let eager: Vec<u32> = all.into_iter().filter(|s| *s > 1000).take(1).collect();
println!("eager {:?} {}", eager, calls.get());
// One iterator chain is lazy: take(1) stops the work after the first match.
calls.set(0);
let lazy: Vec<u32> = articles.iter().map(score).filter(|s| *s > 1000).take(1).collect();
println!("lazy {:?} {}", lazy, calls.get());
}
["Graph stores", "Intro to NoSQL"]
3600
{"architecture": 1, "databases": 1, "graphs": 1, "nosql": 3, "refactoring": 1}
eager [1200] 5
lazy [1200] 1
- Verdict: stdlib. The iterator adapters filter, map, take and flat_map are lazy, and collect, fold or a for loop runs them. A Cell holds the call counter, so the closure score can change it and still be copied into two chains. collect into a Vec between map and filter makes the pipeline eager, so score runs 5 times. The chain without the Vec stops after the first match.
Consequences
Benefits.
- Each step has a name. The reader sees filter, sort and take, not an
if, asortcall and a counter withbreak. Fowler says that pipelines "can clearly capture what otherwise requires long and gnarly loops, and can help make code more readable and thus cheaper and easier to enhance"1. - The steps are small and can be tested alone. A step is a function. A new step goes between two others and does not change them.
- No shared state between the steps. Each step makes a new collection and does not change its input, so pipelines go well with immutable data. Fowler: "Collection-pipelines naturally lend themselves to immutable data structures"1. See Immutability.
- Laziness and parallelism come from the library. A lazy library stops early and needs no full collections between the steps. Some libraries run the same pipeline on many cores. Java says that "The only difference between the serial and parallel versions of this example is the creation of the initial stream"2, which calls
parallelStream()instead ofstream().
Liabilities.
- Copies. An eager pipeline makes a new collection at each step. Fowler notes that "Done naively this involves a lot of copying, which can lead to problems with large amounts of data. However, most of time, it's not a problem in practice"1, because the copies hold references, not the items.
- Overhead of laziness. A lazy pipeline creates objects for its steps and calls them for each item. Kotlin says: "the lazy nature of sequences adds some overhead which may be significant when processing smaller collections or doing simpler computations"3.
- Some steps need all the items. A sort or a group by cannot give its first item before it has read the last one. Java: "Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream"2. Fowler gives the same rule: "Some pipeline operations cannot work with laziness and have to evaluate the whole list"1.
- Side effects become hard to follow. A lazy pipeline calls its functions when the terminal step runs, in an order that the library chooses. Java says that "Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards"2. The
callscounter in the examples is a side effect for the demonstration only. - Debugging. A long chain is one expression, so it has no line for a breakpoint between two steps. Fowler suggests putting an intermediate result into a variable, or adding a print step in a
map1.
When not to use it
Do not use the pattern when the language makes each step heavy. Fowler tried to build pipelines in Java before it had lambdas, and wrote: "the problem is the that syntax is just too messy, overwhelming the clarity that makes collection pipelines so effective. So I gave up and used loops instead"1.
Do not build a long pipeline. Fowler's rule for functions applies to pipelines too: "Larger pipelines need to be factored into separate methods"1. Give a group of steps a name, such as index_by_tag, and call it from a short pipeline.
Use a comprehension when the language has one and the job is one map and one filter. Fowler says that comprehensions "are often easier to work with for simple expressions, but you still need pipelines for their greater flexibility"1. See Comprehension.
Use a loop when the steps share state that is not a collection, for example a running total that decides when to stop, or when a hot loop must avoid the calls and objects of the pipeline. Measure first.
Variants and related patterns
Pipes and Filters. Fowler says that "Collection Pipeline is a special case of the Pipes and Filters pattern"1, the architectural pattern in which independent filters pass data through pipes. In a collection pipeline the data between the steps is a collection.
Unix pipelines. grep, sort, uniq and head connected with | are a collection pipeline whose items are lines of text. Fowler first saw the pattern there1.
Method chains, nested calls and pipe operators. Smalltalk, Ruby, JavaScript, Java, C#, Kotlin and Rust chain methods. Lisp and Python nest calls. Clojure ->>, Elixir and F# |> and the C++ | on views write nested calls as a line.
Lazy pipelines. Java streams, .NET LINQ, Rust iterators, JavaScript iterator helpers, Kotlin sequences, Elixir streams, Ruby Enumerator::Lazy, Python iterators and C++ views are lazy. Elixir says: "Streams are composable, lazy enumerables"4. Ruby says that Enumerator::Lazy "allows constructing chains of operations without evaluating them immediately, and evaluating values on as-needed basis"5. The .NET documentation says: "Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required"6. Lodash adds laziness to array code: "The execution of chained methods is lazy, that is, it's deferred until _#value is implicitly or explicitly called"7, and it can merge steps by "shortcut fusion", which "avoids the creation of intermediate arrays"7.
Iterator adapters. Rust calls the lazy steps adapters: "Functions which take an Iterator and return another Iterator are often called ‘iterator adapters’, as they’re a form of the ‘adapter pattern’"8. Go has no adapters in its standard library, but its iterators are functions that call yield, so a program can write Map, Filter and Take as the Go example does. The Go documentation says: "An iterator is a function that passes successive elements of a sequence to a callback function, conventionally named yield"9. See Iterator and Iterator pattern.
Comprehensions. A comprehension writes a map, a filter and a flat map as one expression. Fowler says that comprehensions "mirror simple collection pipelines"1. See Comprehension.
Replace Loop with Pipeline. The refactoring that turns a loop into a collection pipeline, one step at a time10. See Replace loop with pipeline.
Concurrent pipelines. When the steps run in different threads or processes and pass items through queues or channels, the pipeline is a concurrency pattern. See Concurrent pipeline.
Known uses
- Java: the package
java.util.streamis a library for collection pipelines. Its documentation describes a stream pipeline as a source, intermediate operations and a terminal operation, and it can run the same pipeline in parallel2. - .NET: the LINQ standard query operators, such as
Where,Select,GroupByandOrderBy. The documentation says: "The standard query operators are the keywords and methods that form the LINQ pattern"11. - Python: the
itertoolsmodule gives lazy steps for pipelines. It says that its tools "form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python"12. - JavaScript: array methods for eager pipelines, and the iterator helper methods for lazy pipelines13. Lodash gives chains with
_.chain7. - Kotlin: the collection functions for eager pipelines and
Sequencefor lazy ones. "Sequences offer the same functions as Iterable but implement another approach to multistep collection processing"3. - C++: the ranges library. "Adaptors can be composed into pipelines, so that their actions take place as the view is iterated"14.
References
- Martin Fowler, Collection Pipeline, Introduction; Defining Collection Pipeline; Alternatives; Laziness; Parallelism; Immutability; Debugging; When to Use It; Operation Catalog
- Package java.util.stream, Java SE 25 API, Stream operations and pipelines; Parallelism; Side-effects
- Sequences, Kotlin documentation, Introduction
- Stream, Elixir documentation, Introduction
- class Enumerator::Lazy, Ruby documentation, Introduction
- Deferred execution and lazy evaluation, Microsoft Learn, Deferred execution; Eager and lazy evaluation
- Lodash Documentation, _(value); _.chain
- Module iter, The Rust Standard Library, Adapters; Laziness
- Package iter, Go standard library, Iterators; type Seq
- Martin Fowler, Catalog of Refactorings, Replace Loop with Pipeline, the entry
- Standard query operators overview, Microsoft Learn, Introduction
- itertools, Python documentation, Introduction
- Iterator, MDN Web Docs, Iterator helper methods
- Ranges library, cppreference.com, Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag B105KH Edit this page History Report an error Markdown