【问题标题】:Scala skip when key not found in mapScala 在地图中找不到键时跳过
【发布时间】:2017-07-14 04:16:29
【问题描述】:

当我在Map 中找不到密钥时,我正在尝试执行以下操作

val states = Seq(Ca, Wa, Ny)
val tuples: Seq[Any] = for(state <- states) yield {
  val mapValue: Option[CustomCaseClass] = someMap.get(key)
  mapValue match {
    case Some(value) => {
      //do some operations and return a tuple (String, String)
    }
    case _ => //do nothing, just continue the for loop
  }
}

对于case _,我什么都不想做,简单地继续循环。但是使用上面的代码,我无法在 tuples 上执行 toMap 并且我收到以下错误 -

Cannot prove that Any &lt;:&lt; (String, String)

这是因为它可能并不总是返回 Seq[(String,String)]。我希望能够对tuples 进行操作,并且我只想在找不到该案例时跳过该案例。任何指导表示赞赏。

【问题讨论】:

    标签: scala


    【解决方案1】:

    假设如下设置:

    sealed trait State
    case object Ca extends State
    case object Wa extends State
    case object Ny extends State
    
    val someMap = Map(Ca -> 1, Wa -> 2)
    val states = Seq(Ca, Wa, Ny)
    

    我们可以在同一个for理解中使用Option作为另一个生成器:

    val tuples: Seq[(String, String)] = for {
        state <- states
        value <- someMap.get(state)
    } yield (state.toString, value.toString + "x")
    

    Option 将被隐式转换为 0 到 1 个元素的集合,因此对于 None,将跳过以下所有代码,我们将得到:

    assert(tuples.toMap == Map("Ca" -> "1x", "Wa" -> "2x"))
    

    您还可以在for 中插入任意检查,因此您可以检查密钥是否存在并使用someMap(key),而不是someMap.get(key)

    val tuples2: Seq[(String, String)] = for {
        state <- states
        if someMap.contains(state)
    } yield (state.toString, someMap(state).toString + "x")
    
    assert(tuples2.toMap == Map("Ca" -> "1x", "Wa" -> "2x"))
    

    【讨论】:

      【解决方案2】:

      由于case _ 它返回nothing,所以result 类型为Seq[Any],您可以过滤未找到 元素并执行map

      val tuples: Seq[(String, String)] = 
          states.filter(i => someMap.get(i).nonEmpty).map(value => (myString, myString))
      

      【讨论】:

      • 空大小写返回Unit,而不是nothing。此外,你不需要map.get(i).nonEmpty,你可以简单地使用map.contains(i)
      猜你喜欢
      • 2019-07-17
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多