Take the first 3 positive numbers from a mixed list.

← Streams and Pipelines · Ref: Q1143

Filter with a predicate, then limit with head:

  cat items | filter by isPositive | head 3 > stdout

The head operation takes only the first N items from the stream. Combining filter and head replaces Java's filter().limit() pattern. See Q235 for stream operations. See Q125 for head/tail/skip.

Example

defines module qa.streams.filterhead

  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

    FilterHeadDemo()
      stdout <- Stdout()

      items <- [-2, 5, -1, 8, 3, -4, 7, 12, -6]

      // Take first 3 positive numbers
      firstThree <- cat items | filter by isPositive | head 3 | collect as List of Integer
      stdout.println(`First 3 positives: ${firstThree}`)

      // Stream directly to stdout
      stdout.println("Streamed:")
      cat items | filter by isPositive | head 3 | map with intToString > stdout

Common mistakes

E50060 — EK9 uses 'head N' for limiting stream output, not .limit(). See ek9 -h E50060 for details.

Incorrect:

firstThree <- items.stream().filter(isPositive).limit(3).collect()

Correct:

firstThree <- cat items | filter by isPositive | head 3 | collect as List of Integer
Other ways to ask this
  • Write code to filter positive numbers and take the first three
  • I have a list of mixed integers and need only the first 3 positives
  • Given [-2, 5, -1, 8, 3, -4, 7], produce the first 3 positive values
  • In Java I'd use stream().filter(n -> n > 0).limit(3). Write the EK9 equivalent

Coming from another language?

Java: stream().filter(n -> n > 0).limit(3). Python: itertools.islice(filter(...)). Rust: iter().filter().take(3). EK9: cat | filter by | head 3.

Keywords: take, first, pipeline, stream, head, limit, positive, filter