I have recently started looking at Scala code and I am trying to understand how to go about a problem.
I have a mutable list of objects, these objects have an id: String
and values: List[Int]
. The way I get the data, more than one object can have the same id. I am trying to merge the items in the list, so if for example, I have 3 objects with id 123 and whichever values, I end up with just one object with the id, and the values of the 3 combined.
I could do this the java way, iterating, and so on, but I was wondering if there is an easier Scala-specific way of going about this?
CodePudding user response:
The first thing to do is avoid using mutable data and think about transforming one immutable object into another. So rather than mutating the contents of one collection, think about creating a new collection from the old one.
Once you have done that it is actually very straightforward because this is the sort of thing that is directly supported by the Scala library.
case class Data(id: String, values: List[Int])
val list: List[Data] = ???
val result: Map[String, List[Int]] =
list.groupMapReduce(_.id)(_.values)(_ _)
The groupMapReduce
call breaks down into three parts:
The first part groups the data by the id
field and makes that the key. This gives a Map[String, List[Data]]
The second part extracts the values
field and makes that the data, so the result is now Map[String, List[List[Int]]]
The third part combines all the values
fields into a single list, giving the final result Map[String, List[Int]]