Find the cheapest product in a list.

← Operators and Expressions · Ref: Q1086

Find the minimum with sort ascending + head 1:

  cheapest <- cat products | sort | head 1 | collect as List of Product

Sort + head 1 is the standard min pattern. For the maximum, use a descending comparator with 'sort by'.

See Q1085 for sorting records. See Q1073 for descending sort.

Example

defines module qa.operators.findcheapestproduct

  defines class

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

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

      default operator

  defines function

    descending() as pure
      ->
        left as Product
        right as Product
      <- rtn as Integer: right <=> left

  defines program

    FindCheapestProductDemo()
      stdout <- Stdout()

      products <- List() of Product
      products += Product("Keyboard", 49.99)
      products += Product("Mouse", 19.99)
      products += Product("Monitor", 299.99)
      products += Product("Cable", 9.99)

      //Find cheapest: sort ascending, take first
      cheapest <- cat products | sort | head 1 | collect as List of Product
      stdout.println(`Cheapest: ${cheapest}`)

      //Find most expensive: sort descending, take first
      priciest <- cat products | sort by descending | head 1 | collect as List of Product
      stdout.println(`Priciest: ${priciest}`)

Common mistakes

E50060 — EK9 has no .min() method. Use a stream pipeline: sort ascending, then head 1 to get the smallest.

Incorrect:

      cheapest <- products.min()

Correct:

      cheapest <- cat products | sort | head 1 | collect as List of Product
Other ways to ask this
  • Get the minimum item from a collection using a stream
  • Extract the smallest record from a sorted list
  • In Python I'd use min(). How do I find the minimum in EK9?
  • I have a list of products and need the one with the lowest price

Coming from another language?

Java: Collections.min(list, comparator). Python: min(products, key=lambda p: p.price). Rust: iter().min_by_key(). EK9: cat list | sort | head 1 | collect.

Keywords: head, cheapest, stream, find, smallest, sort, minimum