How do I transform items and collect the results in EK9?

← Streams and Pipelines · Ref: Q978

Use map with to transform each item, then collect as to gather results:

  cat names | map with toUpper | collect as List of String

The map operation applies a function to each element. The collect terminal materializes the stream into a collection.

Example

defines module qa.streams.mapcollect

  defines function

    formatTemperature() as pure
      -> celsius as Float
      <- rtn as String: `${celsius}C`

  defines program

    MapCollectDemo()
      stdout <- Stdout()

      readings <- [18.5, 22.3, 15.0, 28.7, 20.1]

      labels <- cat readings
        | map with formatTemperature
        | collect as List of String

      stdout.println($labels)

Common mistakes

E50060 — EK9 streams use Unix pipe syntax, not Java method chaining. 'stream()' and 'map()' are not methods on List. Write 'cat items | map with fn | collect as Type'.

Incorrect:

      labels <- readings.stream().map(formatTemperature).collect()

Correct:

      labels <- cat readings
        | map with formatTemperature
        | collect as List of String
Other ways to ask this
  • Show me cat with map and collect as in EK9
  • How does stream map with work in EK9?
  • How do I apply a function to every item in a list using streams?

Coming from another language?

Java: stream.map(String::toUpperCase).collect(Collectors.toList()). EK9: cat names | map with toUpper | collect as List of String.

Keywords: pipeline, transform, map, collect, stream