Split list into multiple lists with fixed number of elements Ask Question

Split list into multiple lists with fixed number of elements Ask Question

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"))

ベストアンサー1

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))

おすすめ記事