Scala: Remove none elements from map and flatten

前端 未结 4 707
臣服心动
臣服心动 2021-01-01 16:02

I have a map:

Map(\"key1\" -> Some(\"value1\"), \"key2\" -> None, \"key3\" -> Some(\"value3\"))

I want to remove all None

相关标签:
4条回答
  • 2021-01-01 16:35

    My take using pattern matching is:

    Map("key1" -> Some("value1"), "key2" -> None, "key3" -> Some("value3")).collect {
      case (key, Some(value)) => key -> value
    }
    // Map(key1 -> value1, key3 -> value3)
    

    Collect acts like combined map + filter

    0 讨论(0)
  • 2021-01-01 16:35

    Using partition over the map, like this,

    val (flattened,_) = map.partition(_._2.isDefined)
    
    0 讨论(0)
  • 2021-01-01 16:39

    You can use for-comprehension + pattern-matching:

    for((k, Some(v)) <- yourMap) yield k -> v
    
    0 讨论(0)
  • 2021-01-01 16:44

    My take using for comprehensions:

    val m = Map("key1" -> Some("value1"), "key2" -> None, "key3" -> Some("value3"))
    for( (key,value) <- m if(value.isDefined)) yield (key,value.get)
    
    0 讨论(0)
提交回复
热议问题