如何使用 A 的值作为映射中的键将 Seq[A] 转换为 Map[Int, A]?
我有一个包含类对象的 Seq
,如下所示:
class A (val key: Int, ...)
现在我想使用 将此
每个对象的值作为键,对象本身作为值。那么:Seq
转换为 Map
>key
val seq: Seq[A] = ...
val map: Map[Int, A] = ... // How to convert seq to map?
如何在 Scala 2.8 中高效且优雅地完成此操作?
I have a Seq
containing objects of a class that looks like this:
class A (val key: Int, ...)
Now I want to convert this Seq
to a Map
, using the key
value of each object as the key, and the object itself as the value. So:
val seq: Seq[A] = ...
val map: Map[Int, A] = ... // How to convert seq to map?
How can I does this efficiently and in an elegant way in Scala 2.8?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于 2.8 Scala 已经有了
.toMap
,所以:或者如果您热衷于避免构造元组的中间序列,那么在 Scala 2.8 到 2.12 中:
或者在 Scala 2.13 和 3 中(它们不这样做)没有
breakOut
,但有可靠的.view
):Since 2.8 Scala has had
.toMap
, so:or if you're gung ho about avoiding constructing an intermediate sequence of tuples, then in Scala 2.8 through 2.12:
or in Scala 2.13 and 3 (which don't have
breakOut
, but do have a reliable.view
):映射您的
Seq
并生成元组序列。然后使用这些元组创建一个Map
。适用于所有版本的 Scala。Map over your
Seq
and produce a sequence of tuples. Then use those tuples to create aMap
. Works in all versions of Scala.另外一个 2.8 变体,为了更好的措施,也很高效:
请注意,如果您有重复的键,您将在地图创建过程中丢弃其中一些!您可以使用
groupBy
创建一个映射,其中每个值都是一个序列:One more 2.8 variation, for good measure, also efficient:
Note that if you have duplicate keys, you'll discard some of them during Map creation! You could use
groupBy
to create a map where each value is a sequence:正如 scala 知道将两个元组转换为映射一样,您首先需要将 seq 转换为元组,然后映射 so(如果它是 int,在我们的例子中是 string,string 也没关系):
一般算法是this:
或者总结:
步骤1:Seq -->两个元组
步骤2:两个元组-->地图
示例:
As scala knows to convert a Tuple of two to a map, you would first want to convert your seq to a tuple and then to map so (doesn't matter if it's int, in our case string, string):
The general algorithm is this:
Or to sum up:
Step 1: Seq --> Tuple of two
Step 2: Tuple of two --> Map
Example: