How do I sort a stream and take the top N items in EK9?

← Streams and Pipelines · Ref: Q979

Use sort by to order items, then head N to take the first N:

  cat prices | sort by ascending | head 3 > stdout

head N replaces the break-after-N pattern from other languages. The pipeline stops after emitting N items.

Use > stdout to print results, or collect as to gather into a collection.

Example

defines module qa.streams.sorthead

  defines function

    compareByAmount() as pure
      ->
        left as Float
        right as Float
      <- rtn as Integer: left <=> right

  defines program

    SortHeadDemo()
      stdout <- Stdout()

      expenses <- [45.99, 12.50, 89.00, 23.75, 67.30, 8.99, 155.00]

      stdout.println("Top 3 expenses:")
      cat expenses
        | sort by compareByAmount
        | head 3
        > stdout

Common mistakes

E01070 — EK9 has no break statement (E01070). Use 'head N' in a stream pipeline to take the first N items. See ek9 -h E01070.

Incorrect:

      for expense in expenses
        if count > 3
          break

Correct:

      cat expenses
        | sort by compareByAmount
        | head 3
        > stdout
Other ways to ask this
  • Show me sort by and head in a stream pipeline
  • How do I get the first 3 items after sorting in EK9?
  • What replaces break in EK9 stream loops?

Coming from another language?

Java: stream.sorted().limit(3). Python: sorted(items)[:3]. EK9: cat items | sort by comparator | head 3.

Keywords: break replacement, stream, head, top N, sort, pipeline