Review this EK9 code. Should the loop be a stream pipeline instead?

← Streams and Pipelines · Ref: Q988

The code uses a for loop with an if condition inside to filter and collect results. This works but is not idiomatic EK9.

IDIOMATIC VERSION:

  highScores <- cat allScores
    | filter by isAboveCutoff
    | collect as List of Integer

WHY THE STREAM IS BETTER:

- The intent is clearer — 'filter by isAboveCutoff' states what happens
- No mutable accumulator variable needed
- The filter predicate is a named, testable, reusable function
- The pipeline reads as a data transformation, not imperative steps

WHEN LOOPS ARE APPROPRIATE:

- When you need mutation or side effects at each step
- When the operation is inherently sequential with state between iterations
- When the body does I/O per item (though streams with > stdout handle this too)

In this case, filtering and collecting is a pure data transformation — a stream pipeline is the idiomatic choice.

Example

defines module qa.streams.reviewloopvsstream

  defines function

    isAboveCutoff() as pure
      -> score as Integer
      <- rtn as Boolean?

      passingScore <- 70
      rtn: score > passingScore

  defines program

    ReviewLoopDemo()
      stdout <- Stdout()

      allScores <- [85, 42, 91, 67, 73, 55, 88, 96, 61, 79]

      //Idiomatic: use stream pipeline for filter + collect
      highScores <- cat allScores
        | filter by isAboveCutoff
        | collect as List of Integer

      stdout.println(`High scores: ${highScores}`)
      stdout.println(`Count: ${highScores.length()}`)

Common mistakes

E01010 — EK9 streams use pipe syntax, not Java method chaining. Write 'cat source | filter by fn | collect as Type'.

Incorrect:

      highScores <- allScores.stream().filter(s -> s > cutoff).collect(Collectors.toList())

Correct:

      highScores <- cat allScores
        | filter by isAboveCutoff
        | collect as List of Integer
Other ways to ask this
  • Is this loop idiomatic EK9 or should it use a stream?
  • Assess whether this code follows EK9 best practices
  • This code works but is it the EK9 way?

Coming from another language?

EK9 uses stream pipelines for filtering, transformation, and collection. Loops are for mutation and sequential stateful operations.

Keywords: review, best practice, loop, quality, stream, idiomatic