为什么 Scala 中的 groupBy 会更改列表项的顺序? [英] Why does groupBy in Scala change the ordering of a list's items?

查看:33
本文介绍了为什么 Scala 中的 groupBy 会更改列表项的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码来自 Scala 工作表:

case class E(a: Int, b: String)val l = 列表(E(1, "一"),E(1, "另一个"),E(2, "两个"),E(2, "另外两个"),E(3, "三"))l.groupBy(x => x.a)//res11: scala.collection.immutable.Map[Int,List[com.dci.ScratchPatch.E]] =//   地图(//2 ->列表(E(2,两个),E(2,另外两个)),//1 ->列表(E(1,一个),E(1,另一个)),//3 ->列表(E(3,三))//)

您会注意到 groupBy 返回一个映射,但元素的排序现在与以前不同.知道为什么会发生这种情况吗?避免这种情况的最佳方法是什么?

解决方案

除非您专门使用 SortedMap 的子类型,否则地图(如集合)始终处于未指定的顺序中.由于groupBy"不返回 SortedMap 而只返回一般的 immutable.Map 并且也不使用 CanBuildFrom 机制,我认为您在这里无能为力.

您可以在类似问题的答案中找到有关此主题的更多信息,例如这里.>

如果你想在之后将地图转换为 SortedMap(按其键排序),你可以执行 SortedMap(l.groupBy(_.a).toSeq:_*)(使用 <代码>导入 scala.collection.immutable.SortedMap).不要做 ...toSeq.sortWith(...).toMap 因为这不能保证结果映射中的排序.

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

这篇关于为什么 Scala 中的 groupBy 会更改列表项的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆