I'm trying to map values from each object of a sequence to a map of two keys to a list, but I'm having some issues getting the correct syntax down.

def carConverter(cars: Seq[Car]): Map[(String, Int), List[Car]] = {
for ( car <- cars)
  yield Map[(String,Int), List[Car]] {
  //???
 }
}

What I would like to do is iterate through this sequence, map each car's name (car.name) and year (car.year) to the map as two keys, and append the car to the list of cars correlating to this name and year as the value of the Map. I am also trying to not make use of mutable variables here.

有帮助吗?

解决方案

The entries of maps are just tuples, knowing that you can just map over your Seq[Car] and create those tuples. After that just call toMap and you will get a Map:

cars.map { car =>
  (car.name, car.year) -> car
}.toMap

edit:

If you want to keep duplicates, it is easier to use groupBy:

cars.groupBy(car => (car.name, car.year))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top