zunzelf
zunzelf

Reputation: 85

How to sum/combine each value in List of List in scala

Given the following Scala List:

val l = List(List("a1", "b1", "c1"), List("a2", "b2", "c2"), List("a3", "b3", "c3"))

How can I get:

List("a1a2a3","b1b2b3","c1c2c3")

is it possible to use zipped.map(_ + _) on list that have more than two lists ? or there are any other way to solve this?

Upvotes: 2

Views: 317

Answers (2)

blueiur
blueiur

Reputation: 1507

other solution

scala> val l = List(List("a1", "b1", "c1"), List("a2", "b2", "c2"), List("a3", "b3", "c3"))
scala> l.reduce[List[String]]{ case (acc, current) => acc zip current map { case (a, b) => a + b } }

res2: List[String] = List(a1a2a3, b1b2b3, c1c2c3)

Upvotes: 1

Marth
Marth

Reputation: 24812

You can use the .transpose method :

scala> val l = List(List("a1", "b1", "c1"), List("a2", "b2", "c2"), List("a3", "b3", "c3"))
l: List[List[String]] = List(List(a1, b1, c1), List(a2, b2, c2), List(a3, b3, c3))

scala> l.transpose
res0: List[List[String]] = List(List(a1, a2, a3), List(b1, b2, b3), List(c1, c2, c3))

and then map over the outer list, creating each String using mkString :

scala> l.transpose.map(_.mkString)
res1: List[String] = List(a1a2a3, b1b2b3, c1c2c3)

Upvotes: 8

Related Questions