Here's a solution for a lazy groupBy when the iterator contents are assumed to be clustered (repeated elements next to each other) over the key:
def clusteredGroupBy[B](h: Iterator[B])(f: B => _): Stream[Iterator[B]] = {
if (h.hasNext) {
val firstValue = h.next()
val projection = f(firstValue)
val (head, tail) = h.span(f(_) == projection)
(Iterator(firstValue) ++ head) #:: clusteredGroupBy[B](tail)(f)
} else Stream.empty
}
Any suggestions on how to improve this? Is there anything more native to Scala that does the same?