2015-09-25 66 views
0

假設我有一個具有多屬性值的地圖,我想選擇一個特定的屬性。對於元組的關鍵元素的Scala圖,如何從元組中選擇(項目?)特定項目?

例如,表示具有姓名,性別,年齡,說明的人員的表格的地圖。

在SQL中,我會寫「選擇的人年齡其中名稱=‘任何人’」

我怎麼才能在斯卡拉這種效果?

val people = Map(
"Walter White" -> ("male",52,"bad boy"), 
"Skyler White" -> ("female",42,"morally challenged mom") 
) 

// equivalent of select * from people. This works. 
for ((name,(gender,age,desc)) <- people) println(s"$name is a $age year old $gender and is a $desc") 

// what should be the syntax to get "the age of Walter White is 52"? 
// in SQL, it would be "'The age of Walter White is ' || (select age from people where name='Walter White')" 
// what would it be in Scala? 
println("The age of Walter White is " + people("Walter White")(1)) // not this! 

回答

2

您可以創建一個Person案例類,並創建Person!而非元組新的地圖。

case class Person(name: String, gender: String, age: Int, description: String) 

val persons = people map { case (name, (gender, age, descr)) => 
    name -> Person(name, gender, age, descr) 
} 

這種方式,你可以寫:

persons("Walter White").age    // Int = 52 
persons.get("Skyler White").map(_.age) // Option[Int] = Some(42) 

你也可以使用原來的代碼訪問的年齡:

people("Walter White")._2    // Int = 52 
+1

我喜歡這個答案,因爲彼得給出了幾種檢索數據,但只是想討論權衡。我認爲我們應該總是做'persons.get(「Skyler White」)。map(_。age)'。如果不匹配,SQL不會返回任何行。所以,做人(「沃爾特懷特」)年齡是容易出錯的。 「人們」(「沃爾特懷特」) - 2'更短但不可讀。 – Rahul

+0

太棒了!感謝Peter和Rahul。我不會想出如何避免拋出一個缺少密鑰的異常。 –

+0

@Rahul你是對的,我沒有真正強調在我的答案中使用'Option'的重要性,所以謝謝! –

相關問題