Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala filter list of object if some fields in the object are same

Tags:

scala

I have a list of object PersonInfo, if certain fields in the PersonInfo object are same with another PersonInfo object, i'll say these two objects are duplicated. example:

case class PersonInfo(
    firstName: Instant,
    lastName: Instant,
    ssn: String,
    email: String
)

if two PersonInfo objects have same 'ssn', they are duplicated record. my list looks like this:

val list = List(pi1, pi2, pi3)
pi1 is: PersonInfo("foo", "foo", "123-456-789", "[email protected]")
pi2 is: PersonInfo("bar", "bar", "456-123-789", "[email protected]")
pi3 is: PersonInfo("gee", "gee", "123-456-789", "[email protected])

how can i filter the list to only return list of (pi1 and pi3) since pi1 and pi3 are duplicated:

list.filter(f => pi1.ssn == pi3.ssn) => ???

and I expect it to return List(pi1, pi2)

like image 354
user468587 Avatar asked Jan 20 '26 03:01

user468587


1 Answers

Group them, keep only the duplicates, return as List.

list.groupBy(_.ssn).values.filter(_.length > 1).flatten.toList
like image 59
jwvh Avatar answered Jan 22 '26 18:01

jwvh