Asimov
Asimov

Reputation: 73

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?

Upvotes: 6

Views: 12785

Answers (4)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Concise and clear

Just collect name of the student with a given score.

 student collect { case (name, 10) => name} headOption

use Collect

val students = Map("Scala" -> 10, "Haskell" -> 20, "frege" -> 30)

student collect { case (name, 10) => name} headOption

The above code collects the name of the person whose score is 10 and then do headOption to get the first person. The above code returns None if there is no match.

Scala REPL output

scala> val students = Map("Scala" -> 10, "Haskell" -> 20, "frege" -> 30)
students: scala.collection.immutable.Map[String,Int] = Map(Scala -> 10, Haskell -> 20, frege -> 30)

scala> students collect { case (name, 10) => name }
res3: scala.collection.immutable.Iterable[String] = List(Scala)

scala> students collect { case (name, 10000) => name }
res4: scala.collection.immutable.Iterable[String] = List()

scala> students collect { case (name, 10) => name } headOption
warning: there was one feature warning; re-run with -feature for details
res5: Option[String] = Some(Scala)

Upvotes: -1

ryan
ryan

Reputation: 1084

Check the following:

 val students = Map("N" -> 87, "B" -> 71, "M" -> 95, "X" -> 95)
 students.filter(_._2 == 95).keys
 res3: Iterable[String] = Set(M, X)

Upvotes: 1

Rajesh Kumar J
Rajesh Kumar J

Reputation: 4785

You can use the below code to achieve this

students.filter(_._2 == 71).map(_._1)

Upvotes: 6

easel
easel

Reputation: 4048

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.

Upvotes: 6

Related Questions