Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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() ?
like image 733
Reimeus Avatar asked Mar 02 '12 23:03

Reimeus


People also ask

How do you add a value to a map in scala?

We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.

Does groupBy preserve order scala?

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.

How many parameters does map take in scala?

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.

What does map does in 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.


1 Answers

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))
like image 141
Heiko Seeberger Avatar answered Nov 09 '22 16:11

Heiko Seeberger