Ian Ian - 2 months ago 6
Scala Question

How to sum a list of lists and store them as a lists

Given something like

val list: List[List[Int]] = List(List(5), List(1), List(2), List(3), List(4), List(5, 1), List(5, 2), List(5, 3))


How would one get the list of each sum inner list and return them as a list, i.e.:
List(5,1,2,3,4,6,7,8)


I created a function sum which takes a list and returns the sum. I'm unsure how to apply it to each element in this list.. (New to Scala)

Answer

You can use a map to do this

list.map(_.sum)

or

list.map(innerList => sum(innerList))

Instead of the custom sum function you could use standard lib sum function

scala> val lists = List(List(1, 2), List(3, 4)) 
lists: List[List[Int]] = List(List(1, 2), List(3, 4))

scala> lists.map(_.sum)
res11: List[Int] = List(3, 7)
Comments