Collect filtered stream results into a new List.
← Streams and Pipelines · Ref: Q1136
Use 'collect as' to materialise a stream into a list:
positives <- cat items | filter by isPositive | collect as List of Integer
The result is a new List containing all items that passed the pipeline. See Q954, Q1134.
Example
defines module qa.streams.streamcollectas defines function isPositive() as pure -> item as Integer <- rtn as Boolean: item > 0 defines program StreamCollectAsDemo() stdout <- Stdout() items <- [10, -5, 20, -3, 30, -1] //Collect filtered results into a list positives <- cat items | filter by isPositive | collect as List of Integer stdout.println(`Collected ${$ length positives} items`) cat positives > stdout
Other ways to ask this
- I need to capture a pipeline's output as a List instead of printing it
- In Java I'd use .collect(Collectors.toList()). Write the EK9 equivalent
- Given a filtered stream, materialise the results into a List of Integer
- Store the output of a stream pipeline in a variable using collect as
Coming from another language?
Java: .collect(Collectors.toList()). Python: list(filter(...)). Rust: .collect::<Vec<_>>(). EK9: | collect as List of T.
Keywords: materialise, result, collect, list, capture, pipeline