如何在scala中的地图上跳过地图功能中的键

时间:2016-11-14 00:54:55

标签: scala

给出Map[String, String]

的地图

我想知道如何从地图中跳过一个键

    val m =  Map("1"-> "1", "2"-> "2")
    m.map[(String, String), Map[String, String]].map{
      case(k,v)=>
        if (v == "1") {
          // Q1: how to skip this key
          // Do not need to return anything
        } else {
          // If the value is value that I want, apply some other transformation on it
          (k, someOtherTransformation(v))
        }
    }

4 个答案:

答案 0 :(得分:5)

.collect正在完全按照您的意愿执行,它需要部分函数,如果没有为某个元素定义函数(Map对),则删除该元素:

Map("1"-> "1", "2"-> "2").collect { case (k, v) if v != "1" => (k, v * 2) }
//> scala.collection.immutable.Map[String,String] = Map(2 -> 22)

这里为v != "1"(因为保护)定义了部分函数,​​因此删除了带有v == "1"的元素。

答案 1 :(得分:1)

您可以在case条款中加上“警卫”......

case (k,v) if v != "1" => // apply some transformation on it
case (k,v) => (k,v) // leave as is

...或者只是将您不感兴趣的元素保持不变。

case (k,v) => if (v == "1") (k,v) else // apply some transformation on it

map的输出是一个与输入集合大小相同的新集合,其中所有/部分/没有元素被修改。

答案 2 :(得分:1)

Victor Moroz的答案对于这种情况很有帮助,但是如果您无法决定是否在模式匹配中立即跳过,请使用flatMap

Map("1"-> "1", "2"-> "2").flatMap {
  case (k,v) =>
    val v1 = someComplexCalculation(k, v)
    if (v1 < 0) {
      None
    } else {
      // If the value is value that I want, apply some other transformation on it
      Some((k, someOtherTransformation(v1)))
    }
}

答案 3 :(得分:1)

为什么不.filterNot删除所有不需要的值(根据您的情况)然后.map

示例代码:

Map("1"-> "1", "2" -> "2").filterNot(_._2 == "1").map(someFunction)
//someFunction -> whatever you would implement
相关问题