Filter a list of fruit names to those longer than 4 characters, then uppercase them.

← Streams and Pipelines · Ref: Q1141

Works with String elements the same as any type:

  cat fruits | filter by isLong | map by toUpper > stdout

Use 'reject by' for the inverse filter: cat fruits | reject by isLong > stdout. See Q1134, Q980.

Example

defines module qa.streams.streamstringpipeline

  defines function

    isLong() as pure
      -> item as String
      <- rtn as Boolean?
      minLength <- 4
      rtn: length item > minLength

    toUpper() as pure
      -> item as String
      <- rtn as String: item.upperCase()

  defines program

    StreamStringPipelineDemo()
      stdout <- Stdout()

      fruits <- ["Banana", "Apple", "Cherry", "Date", "Elderberry"]

      stdout.println("Long fruits uppercased:")
      cat fruits
        | filter by isLong
        | map by toUpper
        > stdout

      stdout.println("Short fruits (rejected by isLong):")
      cat fruits
        | reject by isLong
        > stdout

Common mistakes

E50060 — EK9 uses named functions with 'filter by' and 'map by', not lambdas.

Incorrect:

      fruits.stream().filter(s -> s.length() > 4).map(s -> s.toUpperCase())

Correct:

cat fruits
        | filter by isLong
        | map by toUpper
        > stdout
Other ways to ask this
  • I have a list of strings and need to keep only long ones and convert to uppercase
  • In Python I'd use [s.upper() for s in fruits if len(s) > 4]. Write the EK9 pipeline
  • Given fruit names, filter by length then transform to uppercase using filter | map
  • Process a list of strings through a multi-stage pipeline with predicate and transform

Coming from another language?

Java: stream().filter(s -> s.length() > 4).map(String::toUpperCase). Python: list comprehension with filter. EK9: | filter by pred | map by fn.

Keywords: string, reject, map, filter, pipeline, uppercase