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

2020-02-27 03:28发布

问题:

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?

回答1:

input.collect{case (k, Some(v)) => (k,v)}


回答2:

input flatMap {case(k,ov) => ov map {v => (k, v)}}


回答3:

for ((k, Some(v)) <- input) yield (k, v)

It's franza's answer from a later question, but it deserves a re-post here.