0

If I have a Sorted stream like this:

Stream(1, 1, 2, 2, 2, 3, 4, 4, 5)

How can group its content like this:

Stream(List(1, 1), List(2, 2, 2), List(3), List(4, 4), List(5))

Without causing the stream to be completely evaluated right away?

dreigada
  • 83
  • 1
  • 7

1 Answers1

1

You could use something like this but it would only work for sorted streams

def groupValues(stream: Stream[Int]): Stream[List[Int]] = {
    if(stream.isEmpty) {
      Stream.empty
    } else {
      val head = stream.head
      val list = stream.takeWhile(_ == head).toList
      list #:: groupValues(stream.drop(list.size))
    }
  }
Mikel San Vicente
  • 3,831
  • 2
  • 21
  • 39