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

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

问题描述

如果我有一个集合 c 类型为 T ,并且有一个属性 p T (类型为 P ,说),最好的做法是什么

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行,我最终得到一个不可变的地图? (显然,我可以将上面的内容变成一个简单的库实用程序,就像我在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的最佳方式转换成Map-by-Key?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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