Remove all negative numbers from a list, keeping only positives.
← Collections and Data Structures · Ref: Q1162
Use a stream pipeline to filter and collect into a new list:
positives <- cat numbers | filter by isPositive | collect as List of Integer
EK9 does not have a .removeIf() method on lists. Filtering is done through stream pipelines, creating a new collection with only the desired elements. See Q235 for stream operations. See Q122 for collect as.
Example
defines module qa.collections.removematching defines function isPositive() as pure -> num as Integer <- rtn as Boolean: num > 0 intToString() as pure -> num as Integer <- rtn as String: $num defines program RemoveMatchingDemo() stdout <- Stdout() numbers <- [5, -3, 8, -1, 4, -7, 2, -9, 10] stdout.println(`Original: ${numbers}`) // Filter to keep only positives positives <- cat numbers | filter by isPositive | collect as List of Integer stdout.println(`Positives only: ${positives}`) // Stream filtered results directly stdout.println("Streamed positives:") cat numbers | filter by isPositive | map with intToString > stdout
Common mistakes
E50001 — EK9 lists do not have a removeIf() method. Use a stream pipeline with filter and collect to create a new list with the desired elements. See ek9 -h E50060 for details.
Incorrect:
numbers.removeIf(isNegative)
Correct:
positives <- cat numbers | filter by isPositive | collect as List of Integer
Other ways to ask this
- Write code to filter out unwanted elements from a list
- I have a list of integers and need a new list with only positive values
- Given a list with mixed positive and negative numbers, produce a positives-only list
- In Java I'd use stream().filter(n -> n > 0).collect(). Write the EK9 equivalent
Coming from another language?
Java: list.removeIf(n -> n < 0) or stream().filter().collect(). Python: [n for n in nums if n > 0]. Rust: vec.retain(|n| *n > 0). Go: manual loop. EK9: cat | filter by | collect as — always creates a new list.
Keywords: pipeline, remove, negative, filter, positive, collect, list, stream