Reimeus
Reimeus

Reputation: 159784

How to select a object field for map value in Scala using groupby

Here is a newbie scala question. I have a list of people with Person objects with getName() and getYearOfBirth() methods. I am using groupBy to group the Person objects but I only wish to put the names into the map as Person will have lots of additional fields in future. The years will be the keys.

val people = List(
Person("Tom", 1985),
Person("Abigail", 1987),    
Person("Joyce", 1984),
Person("James", 1987),
Person("Scott", 1985),  
Person("Ruth", 1984)
)


var birthdayMap = people.groupBy(x=> x.getYearOfBirth()) // map to getName() ?

Upvotes: 6

Views: 2657

Answers (2)

Xavier Guihot
Xavier Guihot

Reputation: 61666

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))

Upvotes: 0

Heiko Seeberger
Heiko Seeberger

Reputation: 3722

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))

Upvotes: 9

Related Questions