Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from List[String] to List[Int] based on Map

Tags:

scala

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
like image 303
CoolGoose Avatar asked Mar 26 '26 21:03

CoolGoose


2 Answers

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.

like image 97
jwvh Avatar answered Mar 28 '26 22:03

jwvh


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.

like image 33
stefanobaghino Avatar answered Mar 28 '26 20:03

stefanobaghino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!