coder25
coder25

Reputation: 2393

Filter a List based on a parameter in scala

I want to filter a list of Subjects inside a list of student based on a particular subject i.e. "maths" in my case.

Below is the code which defines Student and Subject class.

 case class Student(
    name:String,
    age:Int,
    subjects:List[Subject]
  )

  case class Subject(name:String)

  val sub1=Subject("maths")
  val sub2=Subject("science")
  val sub3=Subject("english")
  val s1=Student("abc",20,List(sub1,sub2))
  val s2=Student("def",20,List(sub3,sub1))

  val sList=List(s1,s2)

Expected Output is

list of students(s1,s2) with filtered subjects as explained below

s1 contains Student("abc",20,List(sub1)) and s2 contains Student("def",20,List(sub1)) i.e sub2 and sub3 is filtered out.

I tried below but it didnot worked

 val filtered=sList.map(x=>x.subjects.filter(_.name=="maths"))

Upvotes: 1

Views: 673

Answers (2)

jwvh
jwvh

Reputation: 51271

If there are students in the list who didn't sign up for the subject in question then I assume you wouldn't want that student in the result list.

val s3=Student("xyz",20,List(sub2,sub3))

val sList=List(s1,s2,s3)
sList.flatMap{s =>
  if (s.subjects.contains(sub1))         // if sub1 is in the subjects list
    Some(s.copy(subjects = List(sub1)))  // drop all others from the list
  else 
    None  // no sub1 in subjects list, skip this student
}

Upvotes: 1

Frederic A.
Frederic A.

Reputation: 3514

What you did doesn't work because you turn the list of students into a list of (list of) subjects.

What I do below is keeping each student, but modify their list of subjects

sList.map(student => student.copy(subjects = student.subjects.filter(_.name=="maths")))

Upvotes: 3

Related Questions