如何获取地图的子集? [英] How to get a subset of a map?

查看:57
本文介绍了如何获取地图的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取地图的子集?

假设我们有

val m: Map[Int, String] = ...
val k: List[Int]

k中所有键都存在于m中的地方.

Where all keys in k exist in m.

现在,我想获取Map m的一个子项,其中只有键在列表k中的对.

Now I would like to get a subsect of the Map m with only the pairs which key is in the list k.

类似于m.intersect(k)的东西,但是intersect并未在地图上定义.

Something like m.intersect(k), but intersect is not defined on a map.

一种方法是使用filterKeys:m.filterKeys(k.contains).但这可能会有点慢,因为对于原始地图中的每个键,都必须在列表中进行搜索.

One way is to use filterKeys: m.filterKeys(k.contains). But this might be a bit slow, because for each key in the original map a search in the list has to be done.

我能想到的另一种方法是k.map(l => (l, m(l)).toMap.在这里,我们只是迭代我们真正感兴趣的键,而不进行搜索.

Another way I could think of is k.map(l => (l, m(l)).toMap. Here wie just iterate through the keys we are really interested in and do not make a search.

是否有更好的(内置)方式?

Is there a better (built-in) way ?

推荐答案

m filterKeys k.toSet

因为SetFunction.

性能: filterKeys本身是O(1),因为它通过使用覆盖的foreachiteratorcontainsget方法生成新映射来工作.访问元素时会产生开销.这意味着新地图不使用额外的内存,而且旧地图的内存也无法释放.

On performance: filterKeys itself is O(1), since it works by producing a new map with overridden foreach, iterator, contains and get methods. The overhead comes when elements are accessed. It means that the new map uses no extra memory, but also that memory for the old map cannot be freed.

如果您需要释放内存并拥有最快的访问权限,一种快速的方法是将k的元素折叠到新的Map中,而不会产生中间的List[(Int,String)]:

If you need to free up the memory and have fastest possible access, a fast way would be to fold the elements of k into a new Map without producing an intermediate List[(Int,String)]:

k.foldLeft(Map[Int,String]()){ (acc, x) => acc + (x -> m(x)) }

这篇关于如何获取地图的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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