I’m writing a small program which will convert a very large file into multiple smaller files, each file will contain 100 lines.
I’m iterating over a lines iteration :
while (lines.hasNext) {
val line = lines.next()
}
I want to introduce a counter and when it reaches a certain value, reset the counter and proceed. In java I would do something like :
int counter = 0;
while (lines.hasNext) {
val line = lines.next()
if(counter == 100){
counter = 0;
}
++counter
}
Is there something similar in scala or an alternative method ?
traditionally in scala you use
.zipWithIndex(this will work with your lines too, as far as they are in Iterator, e.g. has
hasNextandnext()methods, or some other scala collection)But if you need a complicated logic, like resetting counter, you may write it the same way as in java:
Maybe you can tell us why you want to reset counter, so we may say how to do it better?
EDIT
according to your update, that is better to do using grouped method, as @pr1001 proposed: