89685

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

  • Easy question on how to write my entries as a PHP array
  • Objective C Keyword 'in'
  • Pushing data to specific sheets depending upon cell information
  • Find a number that is between two values and return field corresponding to lower value
  • Import txt file from web form to sqlserver database using vbscript
  • Globally registered process is not registered
  • Javascript, map returns undefined
  • Search Facebook by first name with Koala
  • Get highest value from a file using mSL and mIRC
  • How to enforce project-wide unique ids/error codes for easily finding the origin of the error in sou
  • Finding max value in CUDA
  • PHP & cURL proxy - how to make multi-user cookie jar?
  • how to get data attributes of dynamically generated element
  • Responsive design method for collapsing a div
  • Iron Router: How do I send data to the layout?
  • Building Qt project for C++11 standard
  • HTML5 video only works in IE. The other browsers shows the black screen
  • AndEngine Applying Transparancy to AndEngine View
  • Grails calculated field in SQL
  • Keep this build forever option - Jenkins
  • How to define custom class, title, and target in Link Browser for content elements and the new rte_c
  • How do I access an unhandled exception in an MVC Error view?
  • Google Custom Search with transparent background
  • If I include Java 8 in my Android app does that affect which devices it will work on?
  • Email format validation in mvc3 view
  • JFileChooser in front of fullscreen Swing application
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • How to add date and time under each post in guestbook in google app engine
  • JSON with duplicate key names losing information when parsed
  • vba code to select only visible cells in specific column except heading
  • Return words with double consecutive letters
  • coudnt use logback because of log4j
  • python draw pie shapes with colour filled
  • Is there any way to bind data to data.frame by some index?
  • Binding checkboxes to object values in AngularJs
  • How can i traverse a binary tree from right to left in java?
  • To Get the radio button value in ruby on rails
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?