Filtering a list of object based on nested type
algorithm, collections, iteration, scala
Solution
Take the list of persons, and use the filter method on it, checking if each dependent contains a person whose age is 11.
pList.filter(_.dependents.exists(_.age == 11))
This will only check 1 layer deep obviously, so in your example, it will return `Tom` and `Jimmy`, because they are the only `Persons` with a direct dependent who is 11 years old:
Person(
Tom,
50,
List(Person(Bob,20,List(Person(Jimmy,25,List(Person(Harry,11,List()))))), Person(Harry,11,List()))
)
Person(
Jimmy,
25,
List(Person(Harry,11,List()))
)
Alternatively you could make it a little more generic like so:
def dependentAged(age: Int)(person: Person) = person.dependents.exists(_.age == age)
val filtered = pList.filter(dependentAged(11))
Problem
Lets say I have a class as follows: ``` case class Person( name:String, age:Int, dependents:List[Person] ) ``` Lets say I have the following four people: ``` val p1 = Person("Tom",50,List(p2,p4)) val p2 = Person("Bob",20,List(p3)) val p3 = Person("Jimmy",25,List(p4)) val p4 = Person("Harry",11,Nil) ``` My people list is val pList = List(p1,p2,p3,p4) I want to filter this collection to get all the people who have an 11 year old dependent. What is one way to do it? The algorithm can be summed up as For each dependent(d) of each person(p) in pList, if age of dependant(d) is == 11, collect the person(p). How do I express it in scala?