Split list into multiple lists with fixed number of elements

Johnny Everson picture Johnny Everson · Sep 18, 2011 · Viewed 64.2k times · Source

How to split a List of elements into lists with at most N items?

ex: Given a list with 7 elements, create groups of 4, leaving the last group possibly with less elements.

split(List(1,2,3,4,5,6,"seven"),4)

=> List(List(1,2,3,4), List(5,6,"seven"))

Answer

Kipton Barros picture Kipton Barros · Sep 18, 2011

I think you're looking for grouped. It returns an iterator, but you can convert the result to a list,

scala> List(1,2,3,4,5,6,"seven").grouped(4).toList
res0: List[List[Any]] = List(List(1, 2, 3, 4), List(5, 6, seven))