Nested for loop in Scala not iterating through out the file?

Viewed 60

I have first file with data as

A,B,C
B,E,F
C,N,P

And second file with data as below

A,B,C,YES
B,C,D,NO
C,D,E,TRUE
D,E,F,FALSE
E,F,G,NO

I need every record in the first file to iterate with all records in the second file. But it's happening only for the first record.

Below is the code:

import scala.io.Source.fromFile

object TestComparision  {

    def main(args: Array[String]): Unit = {
      val lines = fromFile("C:\\Users\\nreddy26\\Desktop\\Spark\\PRI.txt").getLines
      val lines2 = fromFile("C:\\Users\\nreddy26\\Desktop\\Spark\\LKP.txt").getLines
      var l = 0
      var cnt = 0
      for (line <- lines) {

        for (line2 <- lines2) {

          val cols = line.split(",").map(_.trim)
          println(s"${cols(0)}|${cols(1)}|${cols(2)}")

          val cols2 = line2.split(",").map(_.trim)
          println(s"${cols2(0)}|${cols2(1)}|${cols2(2)}|${cols2(3)}")


        }
      }
    }
  }
1 Answers

As rightly suggested by @Luis, get the lines in List form by using toList:

val lines = fromFile("C:\\Users\\nreddy26\\Desktop\\Spark\\PRI.txt").getLines.toList
val lines2 = fromFile("C:\\Users\\nreddy26\\Desktop\\Spark\\LKP.txt").getLines.toList
Related