Michael Michael - 3 months ago 11
Scala Question

How to split List into segments

Suppose I need to split a given list into segments of 3 like this:

val l = (0 until 5).toList
val segments = l.tails.map(_.take(3)).filter(_.size == 3).toList
segments: List[List[Int]] = List(List(0, 1, 2), List(1, 2, 3), List(2, 3, 4))


I got the
segments
I need but the code is obviously ugly. How would you rewrite it ?

Answer

Use sliding:

val segments: Iterator[List[Int]] = l.sliding(3)

segments.toList
> List[List[Int]] = List(List(0, 1, 2), List(1, 2, 3), List(2, 3, 4))