与this question非常相似,但有点不同。
我有一个List[Family]
,每个Family
都会保留一个List[People]
,我想选择第一个家庭,如果该家庭有一个人名,我正在寻找
case class Person(name: String, age: Int)
case class Family(surname: String, members: List[Person])
def findFamilyByPerson(families:List[Family], personName:String): Family = ???
val per1 = Person("Tina", 4)
val per2 = Person("Mike", 15)
val per3 = Person("Mary", 77)
val per4 = Person("John",34)
val fam1 = Family("Hetfield", List(per1, per2))
val fam2 = Family("McCoy", List(per3, per4))
println(findFamilyByPerson(List(fam1, fam2), "Mary").surname) // should print "McCoy"
我尝试将findFamilyByPerson
定义为:
def findFamilyByPerson(families:List[Family], personName:String): Family = {
families.flatMap(_.members).find(_.name == personName)
}
但是这会返回Option[Person]
,当我想要的是那个人的Family
我猜它与flatMap和Find有关,但不太确定如何解决这个问题。
答案 0 :(得分:2)
def findFamilyByPerson(families:List[Family], personName:String): Option[Family] = {
families.find(_.members.exists(_.name == personName))
}