2

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
3
  • 2
    To which int do you want to convert strings that are not in the map? Commented Jan 4, 2021 at 20:21
  • 1
    Please read the Scaladoc you do not need to be mutable for something like this. You can do this: 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 do val intList = strList.flatMap(x => myMap.get(x)). Commented Jan 4, 2021 at 20:29
  • use filter myMap.filter(x=>strList.contains(x._1)).map(_._2) Commented Jan 5, 2021 at 4:17

2 Answers 2

7

This assumes that any List entry that isn't a Map key should just be ignored.

val strList = List("a", "b", "not exist in map")
val myMap   = Map("a" -> 1, "b" -> 2)

val myList = strList.flatMap(myMap.get)
//myList: List[Int] = List(1, 2)

The order of results, myList, is determined by the order of keys found in strList.

Sign up to request clarification or add additional context in comments.

2 Comments

works great . Flatmap will ignore if certain element not exists. Will not give any error ?
flatMap() will "flatten" a list of Options into a list of elements.
1

The proposed solution works perfectly, but for completeness I'd like to add the following:

val strSet = Set("a", "b", "not exist in map")
val myMap = Map("a" -> 1, "b" -> 2, "c" -> 3)

val myList = myMap.view.filterKeys(strSet).values.toList
//myList: List[Int] = List(1, 2)

This solution's complexity is linear with respects to the number of items in the map, whereas strList.flatMap(myMap.get) is linear with respects to the number of items in the list.

Note that I used a Set instead of a List, otherwise the complexity would have been quadratic. Note further that I used the set itself as a predicate (more about it in the Scala API docs, here for version 2.13.4).

You can play around with this solution here on Scastie.

1 Comment

Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.