--- url: "https://martinfowler.com/articles/collection-pipeline/intersection.html" titulek: "intersection" h1: "intersection" popis: "" jazyk: "" kanonicka: "" drobecky: [] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-14 00:35:22" znaku: 1852 slov: 283 kodovani: "utf-8" sha256: "6ac81670fafeeadd95a1ead3d9625305452785c56288191404827832cf54517e" --- 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. # intersection Retains elements that are also in the supplied collection The notion of a set intersection isn't one that's fundamental to collection pipelines — it naturally fits in better with [nested operator expressons](/articles/collection-pipeline/#NestedOperatorExpressions) — but it is sometimes useful. Rather than use an explicit intersection function, it's often more straightforward to use [filter](filter.html) ruby… ``` [1,1,2,2,3,4].select{|i| [1,3].include? i} # => [1, 1, 3] ``` clojure… ``` (filter #{1 3} [1 1 2 2 3 4]) ;; => (1 1 3) ``` When operating on a list like this, using a filter naturally results in a result that includes duplicates from the source collection, as well as preserving ordering. If you need to remove duplicates, as you would expect with a set operation, you need to follow the intersection with [distinct](distinct.html). Ruby provides an operator for set intersection. ruby… ``` [1,1,2,2,3,4] & [1,3] # => [1, 3] ``` As it's expected to be used in the context of set manipulation, the intersection operator does remove duplicates. Like any infix operator, however, [it's awkward to use in a pipeline](/articles/collection-pipeline/#messy-infix-pipe). Clojure supplies an intersection function defined on its set data structure. To use it in a pipeline with a sequence, you need to convert the sequence to a set first, and convert back to a sequence when you're done if you need that as your result. clojure… ``` (->> [1 1 2 2 3 4] (set) (intersection #{1 3}) (into [])) ;; => [1 3] ```