3

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?

2
  • families.flatMap(_.members).find(_.name == name) does the job. But your data model appears badly chosen, because there is no way to get the surname of Person. Commented Jan 28, 2016 at 15:20
  • @ziggystar depends on how you want to process it, see my answer below Commented Jan 28, 2016 at 18:00

5 Answers 5

7

You can try:

families.flatMap(_.members).find(_.name == name)
Sign up to request clarification or add additional context in comments.

1 Comment

Assuming you want to find only the first match, isn't it less efficient?
2

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.

Comments

1

You could just use flatMap and find:

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

Comments

0

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

Comments

0

if you wanted to find just the family.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.