Trying to convert List[String] into List[Int] based on a Map.
However if the key does not exist I will get a null pointer exception.
How to handle that?
val strList = ["a","b","not exist in map" ]
val myMap = Map(
"a" -> 1,
"b" -> 2
)
var myList = new ListBuffer[Int]()
strList.foreach(k =>
myList += myMap(k)
)
myList.toList
val intList = strList.map(s => myMap.get(x))which will return a List of Options which represent that some values do not exists so you can deal with that latter, you can also do this:val intList = strList.map(x => myMap.getOrElse(key = x, default = 0))if you wan to provide a default value (in this case zero, but you can use what you want) for missing keys. Or if you want to remove / skip missing values doval intList = strList.flatMap(x => myMap.get(x)).myMap.filter(x=>strList.contains(x._1)).map(_._2)