Scala根据该元素的子列表属性从列表中选择一个元素

时间:2018-01-04 02:07:13

标签: scala list

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有关,但不太确定如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

def findFamilyByPerson(families:List[Family], personName:String): Option[Family] = {
     families.find(_.members.exists(_.name == personName)) 
}