问题描述
基本上,我需要从映射中获取给定列表中的键的一组值(按相同的顺序给出键).
Basically I need to get a set of values from a map for a keys in a given list (in the same order keys are given).
val kv = Map("k3" -> "v3", "k1" -> "v1", "k2" -> "v2")
val ks = List("k1", "k2")
我最好能即兴创作的是 foldRight
,胜过 ks
:
The best I could have improvised is foldRight
over ks
:
scala> (ks foldRight List[String]()) { (v, a) => kv(v) :: a }
res7: List[String] = List(v1, v2)
在标准库中还是只有更短的代码,有没有更方便的方法来实现此目的,理想情况下是类似于 kv getVals ks
的东西吗?:)
Are there any more convenient ways to do this in standard lib or just the shorter code, ideally something alike kv getVals ks
? :)
问题当然不是那么重要,只是试图探索良好的风格.
Question is not so important of course, just trying to explore towards good style.
推荐答案
使用flatMap:
ks flatMap { k => kv get k }
或更佳:
ks flatMap (kv get)
并且具有 for
的理解力:
for (k <- ks; v <- kv get k) yield v
但是没有一个像您自己的单行代码那样简洁明了::-)
But none are as succinct or as clear as your own one-liner: :-)
ks map kv
List("k42") map kv // will barf
但是,请注意,这是例外情况-如果 ks
包含未在地图 kv
中定义的键,则可能会引发异常.
However, note that this is exceptional - it may throw an exception if ks
contains a key not defined in the map kv
.
这篇关于从Map中获取值,并在Scala中获得键的给定列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!