Scala 将 Collection 变成 Map-by-key 的最佳方式? [英] Scala best way of turning a Collection into a Map-by-key?

查看:23
本文介绍了Scala 将 Collection 变成 Map-by-key 的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 T 类型的集合 c 并且在 T 上有一个属性 p(输入 P,比如说),做一个 map-by-extracting-key 的最佳方法是什么?

If I have a collection c of type T and there is a property p on T (of type P, say), what is the best way to do a map-by-extracting-key?

val c: Collection[T]
val m: Map[P, T]

一种方法如下:

m = new HashMap[P, T]
c foreach { t => m add (t.getP, t) }

但现在我需要一个可变地图.有没有更好的方法来做到这一点,以便它在 1 行中并且我最终得到一个 immutable Map?(显然我可以将上面的内容变成一个简单的库实用程序,就像我在 Java 中所做的那样,但我怀疑在 Scala 中没有必要)

But now I need a mutable map. Is there a better way of doing this so that it's in 1 line and I end up with an immutable Map? (Obviously I could turn the above into a simple library utility, as I would in Java, but I suspect that in Scala there is no need)

推荐答案

可以使用

c map (t => t.getP -> t) toMap

但请注意,这需要 2 次遍历.

but be aware that this needs 2 traversals.

这篇关于Scala 将 Collection 变成 Map-by-key 的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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