Sort a list of Item records by price and collect the sorted result.

← Streams and Pipelines · Ref: Q1135

Define 'default operator' on the class, then pipe through sort:

  sorted <- cat items | sort | collect as List of Item

'default operator' generates <=> comparing fields in declaration order. See Q1085, Q1073.

Example

defines module qa.streams.streamrecordpipeline

  defines class

    Item
      name <- String()
      price <- Float()

      Item()
        ->
          name as String
          price as Float
        this.name :=: name
        this.price :=: price

      default operator

  defines program

    StreamRecordPipelineDemo()
      stdout <- Stdout()

      items <- List() of Item
      items += Item("Monitor", 299.99)
      items += Item("Mouse", 19.99)
      items += Item("Keyboard", 49.99)

      //Sort by natural ordering (name first, then price)
      sorted <- cat items | sort | collect as List of Item
      stdout.println("Sorted:")
      cat sorted > stdout

Common mistakes

E50001 — EK9 uses stream pipelines for sorting. Define <=> on the class and use cat | sort.

Incorrect:

      items.sort(Comparator.comparing(Item::getPrice))

Correct:

      sorted <- cat items | sort | collect as List of Item
Other ways to ask this
  • I have product objects and need to sort them by price using a stream
  • In Java I'd use stream().sorted(). Write the EK9 record sort pipeline
  • Given a list of items with names and prices, sort and output them
  • Build a stream pipeline that sorts custom records by their natural ordering

Coming from another language?

Java: stream().sorted(Comparator.comparing(Item::getPrice)). Python: sorted(items, key=lambda x: x.price). EK9: cat items | sort | collect.

Keywords: record, stream, collect, order, sort, pipeline