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 => m.name == name)).map(f => f.members.find(m => m.name == name).get) }

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

Answer1:

You can try:

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

Answer2:

You could just use flatMap and find:

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

Answer3:

Using a for comprehension like this,

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

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

Answer4:

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(_.name == "Molly") .map { m => (f.surname, m.name) }} .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

Answer5:

if you wanted to find just the family.

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

人吐槽 人点赞

Recommend

Comment

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

你可以使用这些语言

查看评论:Scala find element in nested List