0

我是 scala 的新手,我的目标是遍历列表并检查列表中的项目是否存在映射作为其键,如果它们存在则返回该键的值。

我做了以下事情:

  def getMatchingValues(listItmes: List[String]) = {
    for (item <- listItems) {
      theMap.keys.foreach { i =>
        if (i.equals(item)) {
          theMap(i)
        }
        "NoMatch"
      }
    }
  }

我想知道在scala中是否有更好的方法来做到这一点?

4

4 回答 4

4

Map 有一种getOrElse方法可以满足您的需求:

def getMatchingValues(listItems: List[String]) = listItems map (theMap.getOrElse(_,"NoMatch"))

至少我认为那是你想要的。这是一个例子:

scala> val theMap = Map("a"->"A", "b" -> "B")
theMap: scala.collection.immutable.Map[String,String] = Map(a -> A, b -> B)

scala> val listItems = List("a","b","c")
listItems: List[String] = List(a, b, c)

scala> listItems map (theMap.getOrElse(_,"NoMatch"))
res0: List[String] = List(A, B, NoMatch)
于 2013-07-23T02:03:49.510 回答
2

flatMap 的可能解决方案:

/* Return Some[String] if found, None if not found, then flatten */
def getMatchingValues(listItems: List[String], theMap: Map[String, String]): List[String] =
    listItems.flatMap(item => theMap.get(item))

/* Same thing with some syntactic sugar */
def getMatchingValuesSmartass(listItems: List[String], theMap: Map[String, String]): List[String] = 
    listItems flatMap theMap.get

val l = List("1", "3", "5", "7")
val m = Map("5" -> "five", "2" -> "two", "1" -> "one")

getMatchingValues(l, m)
getMatchingValuesSmartass(l, m)
于 2013-07-23T02:19:13.027 回答
1

如果我是你,我会做两步。鉴于此Map

val map = Map("a" -> "b", "b" -> "c", "c" -> "d", "d" -> "e")

List

val list = List("a", "c", "e")

起初,我map会对. 如果该项目有价值,则为您提供。OptionList

val mapped = list.map(item => item -> map.get(item))

这会给你这个:

mapped: List[(String, Option[String])] = 
    List(("a",Some("b")), ("c",Some("d")), ("e", None))

在地图上调用get会返回一个包装好的结果。如果有结果,您将获得包装在Some. 否则你会得到一个None. 两者都是Option Option闭包结构的子类,它为您提供空值而无需处理null. 现在你可以map再次达到你的目标。

val result = mapped.map(tuple => tuple._1 -> tuple._2.getOrElse("No match"))
result: List[(String, String)] = List(("a","b"), ("c","d"), ("e","No match"))

getOrElse提取 a 的值,Some如果它是 a ,则回退到参数None

为了让它看起来更专业,我们可以把这个表达式写成一行;)

val result = list.map(item => item -> map.get(item).getOrElse("No match"))

这将为您提供完全相同的结果。

于 2013-07-23T08:07:06.270 回答
1

您可以使用 map.get 方法并使用模式匹配处理结果

list.map { x => map.get(x) match {
  case None => "No match"
  case Some(i) => (x, i)
}}

上面的代码返回一个对列表,其中每对代表列表的元素和映射中关联的值(如果没有找到,则为“不匹配”)

于 2013-07-23T05:23:40.567 回答