scala.collection.Seq.groupBy() 函数是否保留顺序?

Does scala.collection.Seq.groupBy() function preserve the order?

我在想办法:

  1. scala.collection.Seq.groupBy()保留顺序。意思是如果我有 List((true, 2), (true, 8)),并按布尔值的第一个元素执行 groupBy,我是否总是会得到一个 true 列表,它在 8.

  2. 之前有 2 个
  3. toMap 同样的问题。意思是如果我在提到的列表上做一个 toMap,我是否总是会得到 8 作为键 true,因为 8 出现在 2 之后并覆盖它?

我在 Scala 文档中找不到任何关于实现的信息:scala doc。我正在尝试决定是否编写我自己的版本以确保保留顺序。

谢谢!

行为是 documented:

A map from keys to traversable collections such that the following invariant holds: (xs groupBy f)(k) = xs filter (x => f(x) == k)

表示它是根据等于来定义的。

过滤器指定 "The order of the elements is preserved."

因此,是的,按指定顺序保留。

同样,toMap 表示:

Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.

也就是说,有序集合中的最后一个键提供值。