How do I transform stream elements and take the first N in EK9?

← Streams and Pipelines · Ref: Q930

Use 'map with' to transform each element, then 'head N' to take only the first N results.

BASIC PATTERN

  cat source | map with transformer | head N | collect as List of R

The map stage applies a function to every element, changing its type or value. The head stage stops after N elements pass through, discarding the rest.

EXAMPLE: Transform integers to strings, take first 3

  cat [10, 20, 30, 40, 50] | map with intToLabel | head 3 | collect as List of String
  Result: ["Item-10", "Item-20", "Item-30"]

EXAMPLE: Double values, take top 2

  cat [5, 1, 8, 3] | map with doubler | head 2 > stdout
  Output: 10 then 2

Head is efficient because it stops consuming from upstream once N elements have passed.

See Q235 for all operations. See Q125 for head/tail/skip details.

Example

defines module qa.streams.map.head.example

  defines function

    doubler() as pure
      -> number as Integer
      <- rtn as Integer: number * 2

    intToLabel() as pure
      -> number as Integer
      <- rtn as String: `Item-${number}`

  defines program

    MapHeadDemo()
      stdout <- Stdout()

      //Demonstrate transform functions that streams would use with map
      stdout.println(`doubler(10): ${doubler(10)}`)
      stdout.println(`doubler(20): ${doubler(20)}`)

      //Demonstrate intToLabel transform
      stdout.println(intToLabel(30))
      stdout.println(intToLabel(40))
Other ways to ask this
  • How does map with head work in EK9 streams?
  • Can I transform then limit results in an EK9 pipeline?
  • How do I take the first few transformed items from a stream?

Coming from another language?

Java: stream().map(fn).limit(n).collect(). Python: list(map(fn, items))[:n]. Rust: iter().map(fn).take(n).collect(). EK9: cat items | map with fn | head n | collect.

Keywords: take, first, pipeline, stream, head, map, transform, limit