0

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?

1
  • A trivial split operation will have its problems, because then, how would you put a comma inside a cell value? - Writing a CSV parser is not quite that easy. You're better off using one of the readymade CSV parser libraries. Commented Jan 29, 2014 at 22:28

2 Answers 2

3

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"))
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Then

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

and

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.