
Scala filtering a List of Objects
As my Scala experience allegedly increases, being able to filter a List of Object “foo” is very useful:
val name1 = Name(“James”, 5)
val name2 = Name(“John”, 10)
val name3 = Name(“Miles”, 15)
val nameList = List(name1, name2, name3)
List(Name(James,5), Name(John,10), Name(Miles,15))
Make nameList2 _filter _on age > 6:
__ val nameList2 = nameList.filter(.age > 6 ) ___
__ // Comment = List[Name] = **List(Name(John,10), Name(Miles,15))**__
I have left the // Comment (from the original Scala worksheet), to illustrate the contents of nameList2.
If I was to filter on name = “Miles”:
nameList2.filter(_.name ==”Miles”)
This would return:
// Comment List[Name] = List(Name(Miles,15))
:O)