【问题标题】:For a Scala map of key to a tuple, how to select (project?) a specific item from the tuple?对于元组键的 Scala 映射,如何从元组中选择(项目?)特定项目?
【发布时间】:2015-09-25 15:28:38
【问题描述】:

假设我有一张包含多属性值的地图,我想从中选择一个特定的属性。

例如,一张地图,表示一张包含姓名、性别、年龄、描述的人的表格。

在 SQL 中,我会写“从 name='whomever' 的人中选择年龄”

如何在 Scala 中获得这种效果?

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!

【问题讨论】:

    标签: scala hashmap


    【解决方案1】:

    您可以创建一个Person 案例类并使用Persons 而不是元组创建一个新映射。

    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
    

    【讨论】:

    • 我喜欢这个答案,因为彼得展示了几种检索数据的方法,但只想讨论权衡。我认为我们应该一直这样做 persons.get("Skyler White").map(_.age) 。如果没有匹配,SQL 不返回任何行。所以,persons("Walter White").age 很容易出错。 people("Walter White")._2 也更短但不可读。
    • 太棒了!谢谢彼得,也谢谢拉胡尔。我不知道如何避免为丢失的键引发异常。
    • @Rahul 你是对的,我并没有真正强调在我的回答中使用Option 的重要性,所以谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2017-09-20
    • 1970-01-01
    • 2017-04-19
    • 2016-08-21
    • 2011-10-01
    • 2016-04-12
    相关资源
    最近更新 更多