Why does groupBy in Scala change the ordering of a list's items?

后端 未结 2 1647
陌清茗
陌清茗 2020-12-15 05:11

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,         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 06:13

    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:_*) (with import scala.collection.immutable.SortedMap). Don't do ...toSeq.sortWith(...).toMap because that will not guarantee the ordering in the resulting map.

提交回复
热议问题