score:9

Accepted answer
scala> persons groupBy (_.year) mapValues (_ map (_.name))
res9: scala.collection.immutable.Map[Int,scala.collection.immutable.Set[String]] = Map(1984 -> Set(Joyce, Ruth), 1987 -> Set(James, Abigail), 1985 -> Set(Tom, Scott))

score:0

Starting Scala 2.13, most collections are provided with the groupMap method which is an equivalent of a groupBy followed by mapValues:

people.groupMap(_.yearOfBirth)(_.name)
// Map[Int,List[String]] = Map(1985 -> List(Tom, Scott), 1984 -> List(Joyce, Ruth), 1987 -> List(Abigail, James))
// equivalent to people.groupBy(_.yearOfBirth).mapValues(_.map(_.name))

given:

case class Person(name: String, yearOfBirth: Int)
val people = List(Person("Tom", 1985), Person("Abigail", 1987), Person("Joyce", 1984), Person("James", 1987), Person("Scott", 1985), Person("Ruth", 1984))

Related Query

More Query from same tag