sheff1892
sheff1892

Reputation: 48

Scala - Converting List[((String, String), Double)] to List[String,Map[String,Double]]

I've got a list of data that is of the structure List[((String, Double), Double)] where the columns are Car Brand, Car ID and Average price. I want to reformat this data into List[String, Map[Int, Double]]. I'm unsure where to begin.

I suspect that I'm supposed to use something like .map(car => (car.brand, car.carColor, car.purchasePrice) to split the values out, then another map to put them into the structure that I require.

The code to generate the data that I wish to reformat is as follows

val carStats = cars.groupBy(c => (c.brand,
     c.carID)).mapValues(cars => car.map(_.purchasePrice).sum / cars.length).toList

I ultimately want this list to be reformatted into List[String, Map[String, Double]], but efforts so far haven't had much luck.

Upvotes: 1

Views: 183

Answers (1)

b1n0ys
b1n0ys

Reputation: 421

is this what you are looking for ?

val result = carStats.map{case ((brand, id), avg_price) => (brand, id, avg_price)}.groupBy(_._1).mapValues(v => v.map{e => (e._2,e._3)}.toMap).toList

Upvotes: 2

Related Questions