Is there an iterative version of groupBy in Scala?

I have an iterator with a lot of elements, so I cannot convert it to Iterable for groupBy and I do not want all the results to be obtained in memmory. But I know that all objects are ordered by groupBy field, so it seems possible to implement groupBy for sorted iterators ... Is there any method in the scala collection for this?

+3
source share
2 answers

My decision:

 def iterativeGroupBy[T, B](iterO: Iterator[T])(func: T => B): Iterator[List[T]] = new Iterator[List[T]] {
    var iter = iterO
    def hasNext = iter.hasNext

    def next = {
      val first = iter.next()
      val firstValue = func(first)
      val (i1,i2) = iter.span(el => func(el) == firstValue)
      iter = i2
      first :: i1.toList
    }
  }
+4
source

It is strange that groupByit is not on Iterator, but what about this?

val it = Iterator(1, 2, 3)
new Iterable[Int] { def iterator = it }.groupBy(_ % 2 == 0)

This seems to work (although this is by no means guaranteed, given that it must produce the same iterator c each time Iterable).

+3
source

All Articles