This code is from a Scala Worksheet:
case class E(a: Int, b: String)
val l = List(
E(1, "One"),
E(1, "Another One"),
E(2, "Two"),
E(2, "Another Two"),
E(3, "Three")
)
l.groupBy(x => x.a)
// res11: scala.collection.immutable.Map[Int,List[com.dci.ScratchPatch.E]] =
// Map(
// 2 -> List(E(2,Two), E(2,Another Two)),
// 1 -> List(E(1,One), E(1,Another One)),
// 3 -> List(E(3,Three))
// )
You will notice that groupBy returns a map, but that the ordering of the elements are now different to the way they were before. Any idea why this happens, and what the best way is to avoid this?
Unless you specifically use a subtype of SortedMap, a map (like a set) is always in an unspecified order. Since “groupBy” doesn’t return a SortedMap but only a general immutable.Map and also doesn’t use the CanBuildFrom mechanism, I think there’s nothing that you can do here.
You can find more on this topic in answers to similar questions, e.g. here.
Edit:
If you want to convert the map afterwarts to a SortedMap (ordered by its keys), you can do
SortedMap(l.groupBy(_.a).toSeq:_*)(withimport scala.collection.immutable.SortedMap). Don’t do...toSeq.sortWith(...).toMapbecause that will not guarantee the ordering in the resulting map.