Scala: How to create a map over a collection from a set of keys?

Say I have a set of people Set[People]. Each person has an age. I want to create a function, which creates a Map[Int, Seq[People]] where for each age from, say, 0 to 100, there would be a sequence of people of that age or an empty sequence if there were no people of that age in the original collection.

I.e. I'm doing something along the lines

Set[People].groupBy(_.age)

where the output was

Map[Int, Seq[People]](0 -> Seq[John,Mary], 1-> Seq[People](), 2 -> Seq[People](Bill)...

groupBy of course omits all those ages for which there are no people. How should I implement this?

Upvotes: 0

Views: 123

Answers (2)

Giovanni Caporaletti
Giovanni Caporaletti

Reputation: 5556

Configure a default value for your map:

val grouped = people.groupBy(_.age).withDefaultValue(Set())

if you need the values to be sequences you can map them

val grouped = people.groupBy(_.age).mapValues(_.toSeq).withDefaultValue(Seq())

Remember than, as the documentation puts it:

Note: `get`, `contains`, `iterator`, `keys`, etc are not affected by `withDefault`.

Upvotes: 1

Nyavro
Nyavro

Reputation: 8866

Since you've got map with not empty sequences corresponding to ages, you can fill the rest with empty collections:

val fullMap = (0 to 100).map (index => index -> map.getOrElse(index, None)).toMap

Upvotes: 0

Related Questions