将计数器引入scala中的循环

blu*_*sky 3 java scala

我正在编写一个小程序,它将一个非常大的文件转换成多个较小的文件,每个文件将包含100行.

我正在迭代一次迭代:

  while (lines.hasNext) {
      val line = lines.next()
  }
Run Code Online (Sandbox Code Playgroud)

我想介绍一个计数器,当它达到一定值时,重置计数器然后继续.在java中我会做类似的事情:

int counter = 0;
      while (lines.hasNext) {
          val line = lines.next()
if(counter == 100){
 counter = 0;
}
++counter
      }
Run Code Online (Sandbox Code Playgroud)

scala或替代方法中是否有类似的东西?

om-*_*nom 9

传统上你在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
Run Code Online (Sandbox Code Playgroud)

(这也适用于你的行,就像它们在Iterator中一样,例如has hasNextnext()methods,或者其他一些scala集合)

但是如果你需要一个复杂的逻辑,比如重置计数器,你可以用与java中相同的方式编写它:

var counter = 0
while (lines.hasNext) {
  val line = lines.next()
  if(counter % 100 == 0) {
    // now write to another file
  }
}
Run Code Online (Sandbox Code Playgroud)

也许你可以告诉我们你为什么要重置计数器,所以我们可以说如何做得更好?

编辑 根据您的更新,使用分组方法更好,因为@ pr1001建议:

lines.grouped(100).foreach(l => l.foreach(/* write line to file*/))
Run Code Online (Sandbox Code Playgroud)