1

Let's say I have the following array of string:

val lines: List[String] = List("GOOL,1182", "AMZN,1920", "MSFT,124", "APPL,192.2") 

In practice this type of array is typically obtained by reading a csv file.

Conceptually, I would like to

  1. For each line, split it by ","
  2. After splitting all the lines, assign the first column to a List, and the second column to another List.

The approach I came up with is the following:

var col1List = List[String]()
var col2List = List[String]()
lines.foreach{ x => 
  val cols = x split ","
  col1List = col1List ::: List(cols(0))
  col2List = col2List ::: List(cols(1))
}

Afterward, I got the following Lists:

List[String] = List(GOOL, AMZN, MSFT, APPL)
List[String] = List(1182, 1920, 124, 192.2)

Is there a better way to do this in Scala?

3 Answers 3

6

What you are looking for is .unzip method.

Here's an example:

val lines: List[String] = List("GOOL,1182", "AMZN,1920", "MSFT,124", "APPL,192.2")
val (l1, l2) = lines.map(_.split(",")).map(arr => (arr.head, arr.last)).unzip
println(l1, l2)

Result:

(List(GOOL, AMZN, MSFT, APPL),List(1182, 1920, 124, 192.2))
0
4

bottaio is kind-of right, you need unzip. You need NOTHING BUT unzip:

val lines: List[String] = List("GOOL,1182", "AMZN,1920", "MSFT,124", "APPL,192.2")
val (xs, ys) = lines.unzip{ str => val a = str.split(","); (a(0), a(1)) }
println(xs)
println(ys)

// Output:
// List(GOOL, AMZN, MSFT, APPL)
// List(1182, 1920, 124, 192.2)

Notice that unzip itself accepts a function that transforms entries of the list into pairs.

3

This in general, works for all sizes of lines read from .csv file into the lines List:

lines.map(_.split(",")).transpose

In Scala REPL:

    scala> val lines: List[String] = List("GOOL,1182", "AMZN,1920", "MSFT,124", "APPL,192.2")
    lines: List[String] = List(GOOL,1182, AMZN,1920, MSFT,124, APPL,192.2)

    scala> lines.map(_.split(",")).transpose
    res30: List[List[String]] = List(List(GOOL, AMZN, MSFT, APPL), List(1182, 1920, 124, 192.2))

    scala> val lines: List[String] = List("GOOL,1182,23,56", "AMZN,1920,57,21", "MSFT,124,345,987", "APPL,192.2,765,908")
    lines: List[String] = List(GOOL,1182,23,56, AMZN,1920,57,21, MSFT,124,345,987, APPL,192.2,765,908)

    scala> lines.map(_.split(",")).transpose
    res29: List[List[String]] = List(List(GOOL, AMZN, MSFT, APPL), List(1182, 1920, 124, 192.2), List(23, 57, 345, 765), List(56
    , 21, 987, 908))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.