开发者

How to convert a Map[K, Option[V]] to Map[K, V] discarding Nones in Scala? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

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

I have a Map[Symbol, Option[String]] from reading values from a web page, where some might be missing.

I'd like to 'flatten' this to Map[Symbol, String] removing all the None values.

The best I can do so far is

def removeNones[K, V](map: Map[K, Option[V]]): Map[K, V] = 
    map.collect { case kv if kv._2.isDefined => (kv._1, kv._2.get) }
开发者_开发问答

but I really don't like the case, and having to rebuild the Pair.

Can anyone find a nicer expression?


val m = Map('a -> Some("a string"), 'b -> None)

m collect {case(a, Some(b)) => (a, b)}
  // Map('a -> a string)

seems to do the trick.


I think more elegant way will be like this:

val map1 = Map('a -> Some("a"), 'b -> None)
val map2 = for ((k: Symbol, Some(v)) <- map1) yield (k,v)

Let's print the result:

Predef println  map2
> Map('a -> a)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜