0

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 :(

salvob
  • 1,300
  • 3
  • 21
  • 41
  • `filter` it. `map` it to a `tuple`. Call `toMap`? – Boris the Spider Apr 08 '17 at 15:14
  • map it to a tuple it's not what I need. I can't call the toMap (I updated the question to give more insight about this issue). `filter` looks like a good idea, actually. :) I'll give it a try – salvob Apr 08 '17 at 15:18
  • You need to [`flatten` out the `Option`](https://stackoverflow.com/questions/4730842/how-to-transform-scala-collection-of-optionx-to-collection-of-x). – Boris the Spider Apr 08 '17 at 15:19
  • could you give me an example? – salvob Apr 08 '17 at 15:24
  • The problem is that the List type is of Any and not of (String, Int) or Option[(String, Int)]. First make sure the type is correct. Can you not get the tuple into a Some? Then flatten might just work. – Joost den Boer Apr 08 '17 at 16:13
  • you're right... I actually can make the List as `List[Option[(String,Int))]]` ... And then I could do a `flatten` .. Great – salvob Apr 08 '17 at 16:39

2 Answers2

3

Try this:

list.collect{case (k,v) => (k,v)}.toMap
Nyavro
  • 8,806
  • 2
  • 26
  • 33
1

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]
V-Lamp
  • 1,630
  • 10
  • 18