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() ?
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
groupBy as defined on TraversableLike produces an immutable. Map , so you can't make this method produce something else. The order of the elements in each entry is already preserved, but not the order of the keys. The keys are the result of the function supplied, so they don't really have an order.
The Scala Map type has two type parameters, for the key type and for the value type. So a Map[String, Int] maps strings to integers, while a Map[Int, Set[String]] maps integers to sets of strings. Scala provides both immutable and mutable maps. By default, Map is equal to scala.
The scala map function converts one collection A to another B by applying a function to every element in A . Simply put, you can call the map function on your collection, pass it a function, or an anonymous function, and transform each element of the collection.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With