--- url: "https://martinfowler.com/articles/collection-pipeline/flat-map.html" titulek: "flat-map" h1: "flat-map" popis: "" jazyk: "" kanonicka: "" drobecky: [] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-14 00:35:16" znaku: 1428 slov: 217 kodovani: "utf-8" sha256: "d201e1d474042885cd9f53592781f2cf5030a7eed539dd51b63279ed94cb3e91" --- This page describes an operation in the collection pipeline pattern. For more context read: - [Collection Pipeline Article](/articles/collection-pipeline) : An article explaining the collection pipeline pattern - [Operation Catalog](/articles/collection-pipeline#op-catalog) : The list of selected operations that I have these pages for. # flat-map Map a function over a collection and flatten the result by one-level It's common to want to map a function on an input list that returns multiple values in a list, but you don't want the output nested in the same way as the input was. ruby… ``` ["two birds", "three green peas"]. flat_map {|s| s.split} # => ["two", "birds", "three", "green", "peas"] ``` clojure… ``` (mapcat #(clojure.string/split % #"\s+") ["two birds" "three green peas"]) ;; => ("two" "birds" "three" "green" "peas") ``` Logically this is the same as a [map](map.html) followed by a single-level [flatten](flatten.html). ruby… ``` ["two birds", "three green peas"]. map {|s| s.split}. flatten (1) # => ["two", "birds", "three", "green", "peas"] ``` But it's so commonly needed that many platforms provide a flat-map operation. You can also consider it to be the same as taking all the results of the map and concatenating the results together - hence the clojure name of “mapcat”. clojure… ``` (apply concat (map #(clojure.string/split % #"\s+") ["two birds" "three green peas"])) ;; => ("two" "birds" "three" "green" "peas") ```