A PriorityQueue ordered by a comparator, bounded with withSize

The complete source of collectionTypes_priority_queue.ek9, compiled by the EK9 compiler. Shown on collectionTypes.html.

#!ek9
defines module site.collectionTypes.priorityQueue

  defines function

    suitableLength() as pure
      -> text as String
      <- rtn as Boolean?
      minimumLength <- 5
      rtn: length of text > minimumLength

    stringCompare() as pure
      ->
        t1 as String
        t2 as String
      <-
        r as Integer: t1 <=> t2

  defines program

    ShowPriorityQueue()
      stdout <- Stdout()

      qOne <- PriorityQueue("Bill").withComparator(stringCompare)

      qOne += "And"
      qOne += "Ted"
      qOne += "Excellent"
      qOne += "Adventure"
      qOne += "Outrageous"
      qOne += "Bogus"

      //They come out in order by String comparison, not in the order added.
      allEntries <- cat qOne | collect as List of String
      stdout.println(`All entries: ${allEntries}`)

      //Now make a queue that is finite, with just 3 entries
      topThree <- qOne.withSize(3)

      //Access to a list can be done just like this
      stdout.println(`Top three: ${topThree.list()}`)

      //Missy will make the cut!
      topThree += "Missy"
      stdout.println(`After adding Missy: ${topThree.list()}`)

      //Use PriorityQueue to collect up and keep ordered as part of pipeline
      bestTwo <- PriorityQueue() of String
      bestTwo := bestTwo.withSize(2).withComparator(stringCompare)

      //Note this uses allEntries again, but filter before queueing
      cat allEntries | filter by suitableLength > bestTwo
      stdout.println(`Best two longer than five characters: ${bestTwo.list()}`)

Download collectionTypes_priority_queue.ek9

Output

All entries: ["Ted", "Outrageous", "Excellent", "Bogus", "Bill", "And", "Adventure"]
Top three: ["Ted", "Outrageous", "Excellent"]
After adding Missy: ["Ted", "Outrageous", "Missy"]
Best two longer than five characters: ["Outrageous", "Excellent"]