Scala GroupBy保留插入顺序? [英] Scala GroupBy preserving insertion order?

查看:29
本文介绍了Scala GroupBy保留插入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Lists、Maps等中的groupBy方法,在函数之后生成一个Map.

The groupBy method in Lists, Maps, etc., generate a Map after the function.

有没有办法使用 groupBy 生成保留插入顺序的 Map(例如 LinkedHashMap)?

Is there a way to use the groupBy to generate a Map that preserves insertion order (LinkedHashMap, for instance)?

我正在使用 for 循环手动插入,但我想知道其中一个有用的已定义函数是否可以帮助我.

I'm using for loops to insert manually, but I wanted to know if one of the useful already-defined functions could help me.

提前致谢.

推荐答案

groupBy 定义在 TraversableLike 产生一个 immutable.Map,所以你不能让这个方法产生别的东西.

groupBy as defined on TraversableLike produces an immutable.Map, so you can't make this method produce something else.

已经保留了每个条目中元素的顺序,但没有保留键的顺序.键是所提供函数的结果,因此它们实际上没有顺序.

The order of the elements in each entry is already preserved, but not the order of the keys. The keys are the result of the function supplied, so they don't really have an order.

如果您想根据特定键的第一次出现来下订单,这里有一个关于如何做的草图.假设我们想按值/2 对整数进行分组:

If you wanted to make an order based on the first occurrence of a particular key, here's a sketch of how you might do it. Say we want to group integers by their value / 2:

val m = List(4, 0, 5, 1, 2, 6, 3).zipWithIndex groupBy (_._1 / 2)
val lhm = LinkedHashMap(m.toSeq sortBy (_._2.head._2): _*)
lhm mapValues (_ map (_._1))
// Map(2 -> List(4, 5), 0 -> List(0, 1), 1 -> List(2, 3), 3 -> List(6))
// Note order of keys is same as first occurrence in original list

这篇关于Scala GroupBy保留插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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