Java – introducing counters into loops in Scala
I'm writing a small program that converts a very large file into multiple smaller files, each of which will contain 100 lines
I'm going through an iteration:
while (lines.hasNext) { val line = lines.next() }
I want to introduce a counter. When it reaches a certain value, reset the counter and continue In Java, I will do something similar:
int counter = 0; while (lines.hasNext) { val line = lines.next() if(counter == 100){ counter = 0; } ++counter }
Is there something similar in scala or alternative methods?
Solution
It is traditionally used in scala zipWithIndex
scala> List("foo","bar") res0: List[java.lang.String] = List(foo,bar) scala> for((x,i) <- res0.zipWithIndex) println(i + " : " +x) 0 : foo 1 : bar
(this also applies to your rows, just as they are in the iterator, such as the hasnext and next () methods, or some other Scala collections)
But if you need a complex logic, such as resetting counters, you can write it in the same way as in Java:
var counter = 0 while (lines.hasNext) { val line = lines.next() if(counter % 100 == 0) { // Now write to another file } }
Maybe you can tell us why you want to reset the counter, so we can say how to do better?
According to your update, it is better to use the grouping method, because @ pr1001 recommends:
lines.grouped(100).foreach(l => l.foreach(/* write line to file*/))