Split list into multiple lists with fixed number of elements

前端 未结 5 471
独厮守ぢ
独厮守ぢ 2020-12-02 10:17

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 elem

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 11:01

    There is much easier way to do the task using sliding method. It works this way:

    val numbers = List(1, 2, 3, 4, 5, 6 ,7)
    

    Lets say you want to break the list into smaller lists of size 3.

    numbers.sliding(3, 3).toList
    

    will give you

    List(List(1, 2, 3), List(4, 5, 6), List(7))
    

提交回复
热议问题