1

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.

1
  • 1
    Can you share some example input and expected output? I believe you will have many Car Brand and many Car ID for each brand, and you want to group by both and compute the average price for each Card brand + Car ID. Also, can you please tell us which Scala version this has to be done. Finally, why List[(String, Map[String, Double]]? Wouldn't it be better a Map[String, Map[String, Double]]? Commented Oct 2, 2019 at 16:40

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly it, thanks very much. I was struggling to get my head around this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.