scaladictionary

Retrieving key(s) from a Scala map using a value


I currently have a Map in Scala and I need to retrieve the key (or keys!) which match a certain value.

I currently have a map of students and test scores and need to be able to find the students who have scored the value that I input.

My map is as follows:

var students = Map(
 "Neil" -> 87
 "Buzz" -> 71
 "Michael" -> 95
)

How could I search through this map to find the student who had scored 71 for example and then return the key?


Solution

  • First off, you should probably be using a val instead of the var, like this: val students = Map("Neil" -> 97, "Buzz" -> 71, "Michael" -> 95)

    Secondly, the method you probably want is called find.

    Something like this students.find(_._2 == 71).map(_._1)

    Which basically says, find me the first (key, value) pair where the value (_._2 == 71) is 71, and then throw out the value .map(_._1). It's going to be wrapped in an Option because there might be 0 matches.

    That said, unless you have something to ensure a value never appears more than once, you might be happier with the results from filter.