Subdivide a list into list of lists [duplicate]

2019-08-01 22:02发布

问题:

This question already has an answer here:

  • Split list into multiple lists with fixed number of elements 5 answers

I would like to subdivide a list into lists of list with a max size for each sublist. For example, given List(1,2,5,3,90,3,4,1,0,3) and max size of sublists defined as 4, I would like to get List(List(1,2,5,3), List(90,3,4,1), List(0,3)) back.

This is what has already been done:

val l: List[Int] = ???
val subSize: Int = 4
val rest: Int = if(l.size % subSize == 0) 1 else 0

val subdivided: List[List[Int]] = for{
  j <- List.range(0, l.size/subSize - rest, 1)
}yield{
  for{
    i <- List.range(subSize*j,subSize*j+3,1)
    if(i < l.size)
  }yield{
    l(i)
  }
}

Is there a better, more functional way of doing this?

回答1:

Yes there is, using grouped.

scala> List(1,2,5,3,90,3,4,1,0,3).grouped(4).toList
res1: List[List[Int]] = List(List(1, 2, 5, 3), List(90, 3, 4, 1), List(0, 3))

Note that grouped actually returns an Iterator, so that you can lazily traverse the collection without doing all the computation at once.