4

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
5
  • Can you explain why you want to do this? What is the problem with converting to a suitable collection type before sorting? Commented Sep 4, 2019 at 15:36
  • @Tim Performance concerns. We have a very large collection to sort, and very tight memory allocation and latency requirement. Commented Sep 4, 2019 at 15:38
  • What is type of priority? Integer? Commented Sep 4, 2019 at 16:22
  • @KrzysztofAtłasik Ya it is an Int Commented Sep 4, 2019 at 16:23
  • @texasbruce Can it take any value or only the limited set (like [1,2,3..100])? Maybe you should go for counting sort? Commented Sep 4, 2019 at 16:26

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

For Scala 2.12 and below, I use a custom CanBuildFrom to allow map/collect to transform into a different collection type. scala.collection.breakOut does this automatically:

import scala.collection.breakOut

fooMap.collect[Foo, Seq[Foo]]  { 
  case (k, f) if k.startWith("F") => f
}(breakOut).sortBy(_.priority)

For Scala 2.13 and above, since CanBuildFrom and breakOut is no longer available and Views are more reliable, I would use a view as stated in @volty-de-qua 's answer, since only from 2.13 that collection.Views have been vastly simplified and should now work reliably.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.