I have a Map of String -> Foo and I want to get a sorted collection of Foos by Foo.priority:
fooMap.collect { case (k, f) if k.startWith("F") => f }.toSeq.sortBy(_.priority)
How can I avoid the intermediate toSeq? Can I create a new collection and insert by the ordering? Maybe something like:
fooMap.collect { case (k, f) if k.startWith("F") => f }.to[Seq](orderedCanBuildFrom) //does not work
You can't sort an Iterable directly, and the insertion sort that you describe is going to be very slow for large collections.
The best option is probably to convert to Array and use the scala.util.sorting package which provides in-place sorting of Arrays.
Since you say you are tight on memory and latency, try this
fooMap.view.filter(_._1.startsWith("F")).map(_._2).toSeq.sortBy(_.priority)
Otherwise consider buying more memory and/or speed :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With