Scala find element in nested List

Consider the following example:

case class Person(name: String, age: Int) case class Family(surname: String, members: List[Person]) val families = List( Family("Jones", List(Person("Indiana", 50), Person("Molly", 20))), Family("Black", List(Person("Jack", 55), Person("Derek", 12))))

I want to write a function that finds a person with a certain name in a List[Family] object. This is my current solution:

def find(name: String, families: List[Family]): Option[Person] = { families.find(f => f.members.exists(m => == name)).map(f => f.members.find(m => == name).get) }

Is there a more efficient and elegant (and functional) way to achieve this?


You can try:

families.flatMap(_.members).find( == name)


You could just use flatMap and find:

families.flatMap(fam => fam.members).find(m => == name)


Using a for comprehension like this,

for (f <- families; m <- f.members if == name) yield m

Namely for each family member pick those whose name is as desired.


Functionally I would prefer this way (added surname too, you probably need it, it makes it a bit more complicated):

families.flatMap { f => f.members .find( == "Molly") .map { m => (f.surname, }} .headOption //> res0: Option[(String, String)] = Some((Jones,Molly))

and if you want all people with the given name, just replace .find with .filter and remove .headOption


if you wanted to find just the family.

families.find(f => f.members.exists( == name))

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Scala find element in nested List