Question

I have structure like that :

List(
   Model("Name" -> "first"
         "Items" -> Map("a"->1,"b"->2)),
   Model("Name" -> "Second",
         "Items" -> Map("d"->2,"e"->3)))

And I am trying to get the sum of items as following:

List(
   Model("Name" -> "first"
         "Items" -> 3,
   Model("Name" -> "Second",
          "Items" -> 5)

Any idea of how I could do that in a short and good scala way?

thanks

Was it helpful?

Solution

Assuming Model is a subtype of scala.Product, something like this might do the trick.

modelList.map { m =>
  m.copy(
    items = m.items.values.foldLeft(0) { _ + _ }
  )
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top