Filter a list to items that are both positive and even.
← Streams and Pipelines · Ref: Q1144
Chain multiple filter stages with the pipe operator:
cat items | filter by isPositive | filter by isEven | collect as List of Integer
Each filter uses a separate pure predicate function. The pipe operator chains stages naturally, like Unix pipes. See Q235 for stream operations. See Q237 for streams vs loops.
Example
defines module qa.streams.chainfilters defines function isPositive() as pure -> num as Integer <- rtn as Boolean: num > 0 isEven() as pure -> num as Integer <- rtn as Boolean: num mod 2 == 0 intToString() as pure -> num as Integer <- rtn as String: $num defines program ChainFiltersDemo() stdout <- Stdout() items <- [-5, 2, -3, 8, 7, -4, 6, 1, 10, -2, 0] // Chain two filters: positive AND even positiveEvens <- cat items | filter by isPositive | filter by isEven | collect as List of Integer stdout.println(`Positive and even: ${positiveEvens}`) // Stream directly to stdout stdout.println("Streamed:") cat items | filter by isPositive | filter by isEven | map with intToString > stdout
Common mistakes
E50030 — Stream filter predicates must return Boolean. A function used with 'filter by' must return Boolean, not Integer. See ek9 -h E50030 for details.
Incorrect:
<- rtn as Integer: num > 0
Correct:
<- rtn as Boolean: num > 0
Other ways to ask this
- Write code to chain two filter stages in a stream pipeline
- I have a list of integers and need only those that are positive AND even
- Given a mixed integer list, select values that pass two predicate tests
- In Java I'd use stream().filter(n -> n > 0).filter(n -> n % 2 == 0). Write the EK9 equivalent
Coming from another language?
Java: stream().filter(pred1).filter(pred2). Python: filter(pred2, filter(pred1, iterable)). Rust: iter().filter().filter(). EK9: cat | filter by pred1 | filter by pred2.
Keywords: multiple, predicate, positive, stream, chain, pipeline, filter, pipe, even