Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an Iterable without creating intermediate Seq?

Tags:

scala

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
like image 483
SwiftMango Avatar asked Sep 19 '25 15:09

SwiftMango


2 Answers

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.

like image 173
Tim Avatar answered Sep 21 '25 10:09

Tim


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 :).

like image 40
Volty De Qua Avatar answered Sep 21 '25 09:09

Volty De Qua