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

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

问题描述

listBy方法在列表,地图等中,生成一个Map后的函数。

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

有没有办法使用groupBy来生成保存插入顺序的映射(例如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.

提前感谢。 上定义的

Thanks in advance.

推荐答案

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 Group通过保留插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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