如何使用 A 的值作为映射中的键将 Seq[A] 转换为 Map[Int, A]? [英] How to convert a Seq[A] to a Map[Int, A] using a value of A as the key in the map?
本文介绍了如何使用 A 的值作为映射中的键将 Seq[A] 转换为 Map[Int, A]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Seq
包含一个类的对象,如下所示:
I have a Seq
containing objects of a class that looks like this:
class A (val key: Int, ...)
现在我想把这个Seq
转换成一个Map
,使用每个对象的key
值作为key,以及对象本身作为价值.所以:
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?
如何在 Scala 2.8 中以优雅的方式高效地执行此操作?
How can I does this efficiently and in an elegant way in Scala 2.8?
推荐答案
映射您的 Seq
并生成一个元组序列.然后使用这些元组创建一个 Map
.适用于所有 Scala 版本.
Map over your Seq
and produce a sequence of tuples. Then use those tuples to create a Map
. Works in all versions of Scala.
val map = Map(seq map { a => a.key -> a }: _*)
这篇关于如何使用 A 的值作为映射中的键将 Seq[A] 转换为 Map[Int, A]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文