Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use takeWhile with an Iterator in Scala

I have a Iterator of elements and I want to consume them until a condition is met in the next element, like:

val it = List(1,1,1,1,2,2,2).iterator
val res1 = it.takeWhile( _ == 1).toList
val res2 = it.takeWhile(_ == 2).toList

res1 gives an expected List(1,1,1,1) but res2 returns List(2,2) because iterator had to check the element in position 4.

I know that the list will be ordered so there is no point in traversing the whole list like partition does. I like to finish as soon as the condition is not met. Is there any clever way to do this with Iterators? I can not do a toList to the iterator because it comes from a very big file.

like image 930
tonicebrian Avatar asked Jul 17 '13 13:07

tonicebrian


1 Answers

The simplest solution I found:

val it = List(1,1,1,1,2,2,2).iterator
val (r1, it2) = it.span( _ == 1)

println(s"group taken is: ${r1.toList}\n rest is: ${it2.toList}")

output:

group taken is: List(1, 1, 1, 1)
rest is: List(2, 2, 2)

Very short but further you have to use new iterator.

With any immutable collection it would be similar:

  • use takeWhile when you want only some prefix of collection,
  • use span when you need rest also.
like image 145
Waldemar Wosiński Avatar answered Sep 18 '22 18:09

Waldemar Wosiński