Is there are iterative version of groupBy in Scala?
scala, scala-collections
Solution
My solution:
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
}
}
Problem
I have iterator with a lot of items so I can't convert it to Iterable for groupBy and don't want to sotre all results in memmory. But I know that all object are ordered by groupBy field so it seems possible to implement groupBy for sorted iterators... Is there already some method in scala collection to do this?