0

I am trying to split a string from a CSV on a method. There are two values seperated by one comma.

I use map to create a new List[(String, String)] but when I split, it returns an Array. If I use .toList immediately after the split(",") then it joins them back together, returning a List(String) which makes the split obsolete, and if I use .toList outside of the map, then it returns List[Array(String)].

When I use splitAt(2) it returns the correct datatype but it doesn't split at the comma. Is there a way for the split function to split into two Lists rather than Array?

EDIT: Code:

val getlines = some csv...

val splitList = getlines.map(_.split(",").toList) // returns List[List(String)]
val splitList = getlines.map(_.split(",")).toList // returns List[Array(String)]
val splitList = getlines.map(_.split(",")) // returns List[Array(String)]
Mario Galic
  • 47,285
  • 6
  • 56
  • 98

2 Answers2

4

Based on Convert a Scala list to a tuple?, assuming you have List[String] like so

val lines =
  List(
    "a1,a2",
    "b1,b2",
    "c1,c3"
  )

then

lines.map(_.split(",") match { case Array(a, b) => (a, b) })

outputs

res1: List[(String, String)] = List((a1,a2), (b1,b2), (c1,c3))

However, this might fail at runtime if you have a bad row, say "a1,", in which case consider wrapping it in a Try, or filtering out the bad rows like so

lines.flatMap(_.split(",") match {
  case Array(a, b) => Some((a, b))
  case _ => None
})
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
1

assuming you have a string with comma:

scala> val csvLine = "something,another"
csvLine: String = something,another

scala> csvLine.split(",")
res3: Array[String] = Array(something, another)

scala> res3.toList
res4: List[String] = List(something, another)

this works as expected

if you do have a list of rows, use flatMap:

scala> val csv = List("line1,column2", "line2,column2")
csv: List[String] = List(line1,column2, line2,column2)

scala> csv.flatMap(line => line.split(","))
res5: List[String] = List(line1, column2, line2, column2)
pedrorijo91
  • 7,635
  • 9
  • 44
  • 82