Convert cvs string into list of strings

val lines : String = ("a1 , test1 , test2 , a2 , test3 , test4")

I'd like to convert this to a list of Strings where each string in the list contains 3 elements so above list is converted to 2 element list of strings containing "a1 , test1 , test2" and "a2 , test3 , test4"

One option I have considered is to iterate over each cvs element in the string and if on an element which is the current third element then add then add the previous elements to a new string. Is there a more functional approach?


grouped partitions them into fixed groups with a value n.

scala> lines.split(",").grouped(3).toList
res0: List[Array[String]] = List(Array("a1 ", " test1 ", " test2 "), Array(" a2 ", " test3 ", " test4"))

The answer by @Brian suffices; for an output formatted as

 "a1 , test1 , test2" and "a2 , test3 , test4"

consider for instance

scala> val groups = lines.split(",").grouped(3).map { _.mkString(",").trim }.toList
groups: List[String] = List(a1 , test1 , test2, a2 , test3 , test4)


scala> groups(0)
res1: String = a1 , test1 , test2


scala> groups(1)
res2: String = a2 , test3 , test4

Need Your Help

Error in installation of Magento on wamp server (The connection was reset)

wordpress magento wamp

It keeps saying "The connection was reset" while I'm trying to open magento project under "Your Projects" on the wamp dashboard.

ASP.NET MVC async call a WCF service wcf asynchronous callback

After complete of asynchronous call to WCF service I want set success message into session and show user the notification .