How to split a list into segments

Suppose I need to break this list into segments 3 as follows:

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 need it segments, but the code is clearly ugly. How would you rewrite it?

+4
source share
1 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))
+6
source

Source: https://habr.com/ru/post/1651684/


All Articles