How do I sort a list of dates in ascending order using a stream pipeline?

← Streams and Pipelines · Ref: Q1197

EK9 stream pipelines sort any type that supports the <=> operator. Since Date has built-in comparison, sort works directly.

SORT DATES

  dates <- [2024-12-25, 2024-01-01, 2024-07-04]
  sorted <- cat dates | sort | collect as List of Date

The sort stage uses the type's <=> operator. No Comparator needed for built-in types.

COMBINED PIPELINE

  cat dates | sort | head 2 | collect as List of Date   first two chronologically

This works identically for Date, Time, Integer, String, Money, Duration — any type with <=> is sortable in a stream.

See Q235 for stream operations reference. See Q120 for sort details. See Q542 for date comparison.

Example

defines module qa.streams.sortdates

  defines program

    StreamSortDatesDemo()
      stdout <- Stdout()

      // === DATE LIST ===

      dates <- [2024-12-25, 2024-01-01, 2024-07-04, 2024-03-17, 2024-11-28]
      stdout.println(`Original: ${dates}`)

      // === SORT ASCENDING ===

      sorted <- cat dates | sort | collect as List of Date
      stdout.println(`Sorted: ${sorted}`)

      // === FIRST TWO CHRONOLOGICALLY ===

      firstTwo <- cat dates | sort | head 2 | collect as List of Date
      stdout.println(`First two: ${firstTwo}`)

      // === LAST TWO CHRONOLOGICALLY ===

      lastTwo <- cat dates | sort | tail 2 | collect as List of Date
      stdout.println(`Last two: ${lastTwo}`)

      // === SORT AND DEDUPLICATE ===

      datesWithDuplicates <- [2024-01-01, 2024-07-04, 2024-01-01, 2024-12-25, 2024-07-04]
      unique <- cat datesWithDuplicates | sort | uniq | collect as List of Date
      stdout.println(`Unique sorted: ${unique}`)

      // === DIRECT OUTPUT ===

      stdout.println("All dates sorted:")
      cat dates | sort > stdout

Common mistakes

E50060 — List has no sort() method. EK9 uses stream pipelines for sorting: cat the list, pipe through sort, and collect the result. See ek9 -h E50030 for details.

Incorrect:

sorted <- dates.sort()

Correct:

sorted <- cat dates | sort | collect as List of Date
Other ways to ask this
  • Sort Date values in a stream pipeline and collect the result.
  • I need to order a list of holidays chronologically using cat and sort.
  • In Java I used Stream.sorted() on LocalDate — what is the EK9 equivalent?

Coming from another language?

Java: dates.stream().sorted().collect(Collectors.toList()). Python: sorted(dates). Rust: dates.sort(). Go: sort.Slice(dates, func). EK9: cat dates | sort | collect as List of Date — Unix pipe syntax, implicit Comparator from <=> operator.

Keywords: collect, sort, cat, ascending, chronological, list, stream, pipeline, date, order