scaladictionarycollections

how to find from map with default values for failures


I have a sequence of Students

val students = Seq(Student("Roy"),Student("James"),Student("Rita"))

Have a map of student to marks

val myMap = Map(Student("Roy") -> "100",Student("Rita")-> 95)

Need a resulting sequence of marks, with marks for 'missing' students being defaulted to 0.0

val resultSeq = Seq(100 , 0 , 95)

How can I achieve this in a single pass of students sequence - students being matched based on their name.


Solution

  • An efficient way to do this is to create a new Map that goes from Student.name to test score, and then use getOrElse on that Map (as described in the comments):

    val nameMap = myMap.map { case (k, v) => k.name -> v }
    
    students.map(student => nameMap.getOrElse(student.name, 0))
    

    You can do this without the temporary Map but it is going to be slower on longer lists.

    students.map(student =>
      myMap.find(pair => pair._1.name == student.name).fold(0)(_._2)
    )