简体   繁体   English

将Map [K,Option [V]]转换为Map [K,V]的更好方法

[英]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. 我有一些代码生成一个Map ,其中值是Option类型,我当然想要一个只包含实际值的地图。

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的答案,但值得重新发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为将集合元素添加到Map [K,Set [V]]的创建状态转换的更好方法 - Better way to create state transformation for adding set elements to Map[K, Set[V]] 可尝试[尝试[(K,V)]]尝试[Map [K,V]] - Iterable[Try[(K, V)]] to Try[Map[K, V]] 将RDD [(K,V)转换为Map [K,List [V]] - Convert RDD[(K,V) to Map[K,List[V]] 如何使用 Circe 对 Map[K,V] 进行编码 - How to Encode Map[K,V] using Circe 如何使用Map([K,V])而不是Map [K,V]创建Map构造函数? - How to create a Map constructor using Map([K,V]) instead of Map[K,V]? Scala:如何从Set [K]和从K到V的函数创建Map [K,V]? - Scala: How to create a Map[K,V] from a Set[K] and a function from K to V? Scala:将Map [K,V]转换为IntMap [V]的最有效方法是什么? - Scala: What is the most efficient way convert a Map[K,V] to an IntMap[V]? 如何通过解析 CSV 文件来创建 Map[K, V] 和 Seq[A]? - How to create Map[K, V] and Seq[A] by parsing CSV file? map.updated(k,v)和map +(k,v)之间*有任何区别吗? 我在一个而不是另一个上遇到编译错误 - Is there *any* difference between map.updated(k,v) and map + (k,v)? I'm getting a compile error on one but not the other 读取一个文件作为Map(K,V)并通过V作为键,同时读取第二个文件作为Map - Reading one file as Map(K,V) and pass V as keys while reading the second file as Map
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM