简体   繁体   中英

Better way of converting a Map[K, Option[V]] to a Map[K,V]

I have some code that is producing a Map where the values are Option types, and I really of course want a map containing only the real values.

So I need to convert this, and what I've come up with in code is

  def toMap[K,V](input: Map[K, Option[V]]): Map[K, V] = {
    var result: Map[K, V] = Map()
    input.foreach({
      s: Tuple2[K, Option[V]] => {
        s match {
          case (key, Some(value)) => {
            result += ((key, value))
          }
          case _ => {
            // Don't add the None values
          }
        }
      }
    })
    result
  }

which works, but seems inelegant. I suspect there's something for this built into the collections library that I'm missing.

Is there something built in, or a more idiomatic way to accomplish this?

input.collect{case (k, Some(v)) => (k,v)}
input flatMap {case(k,ov) => ov map {v => (k, v)}}
for ((k, Some(v)) <- input) yield (k, v)

从后来的问题来看,这是franza的答案,但值得重新发布。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM