2016-12-12 93 views
1

我目前在scala中有一個Map,我需要檢索與特定值匹配的密鑰(或密鑰!)。使用值在Scala中檢索密鑰

我目前有一張學生地圖和考試成績,需要能夠找到獲得我輸入的價值的學生。

我的地圖如下:

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

我怎麼會通過這個地圖搜索找到誰曾打進71例如,然後返回鍵的學生嗎?

在此先感謝。

+0

你嘗試過什麼? :) –

+0

我已經嘗試了很多地圖方法,但他們似乎都在關注基於關鍵值而不是其他方式重新獲取值。 – Asimov

+0

Like'students.filter {(key,value)=> value> 50}'? –

回答

1

首先,你或許應該使用一個val代替var,就像這樣:val students = Map("Neil" -> 97, "Buzz" -> 71, "Michael" -> 95)

其次,你可能想的方法被稱爲find

像這樣的事情students.find(_._2 == 71).map(_._1)

這基本上說,我找的第一個(鍵,值)對,其中值(_._2 == 71)是71,然後扔出去的價值.map(_._1)。它將被包裹在一個選項中,因爲可能有0個匹配項。這就是說,除非你有東西確保一個值永遠不會出現超過一次,否則你可能會對filter的結果感到高興。

+0

答案可能已被編輯:「我需要檢索密鑰(或密鑰!)」。所以它看起來像「過濾器」是正確的選擇 –

2

您可以使用下面的代碼來實現這一

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

檢查以下內容:

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

簡潔明瞭

僅僅收取與給定的分數學生的名字。

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

使用Collect

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

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

上面的代碼收集,其得分爲10,然後做headOption拿到第一人的人的名字。如果沒有匹配,上面的代碼返回None。

斯卡拉REPL輸出

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)