Reputation: 1370
I have a List of values that could be None
val list = List(("apples",1), ("oranges",3), ("avocado",4), None, ("pears",10))
how can i transform this into a Map like :
Map("apples"->1, "oranges"->3, "avocado"->4, "pears"->10)
that skips the null elements?
I can't use a toMap
to list
because it gives me the error:
error: Cannot prove that Option[(String, Int)] <:< (T, U).
I was thinking of something like this:
val m = list.map(x => x match{case Some(x) => x._1->x._2
case None => None})
but obviously I am missing something :(
Upvotes: 0
Views: 1113
Reputation: 1678
You can do .flatten
on the list to get only the non-None elements, the do a .toMap
:
list // : List[Option[(String,Int)]]
.flatten // : List[(String,Int)]
.toMap //: Map[String, Int]
Upvotes: 1