I have a function that receives a list of objects. I want to partition that list in groups of fixed size, do something with the groups and return a list of objects in the same order that I received them.
I'm using the function grouped
, from the List
API. Something like this:
val listOfLists = inputList.grouped(FIXED_SIZE).toList
The scala-lang site is down, so what I see on the documentation of the method is:
/** Partitions elements in fixed size ${coll}s.
* @see [[scala.collection.Iterator]], method `grouped`
*
* @param size the number of elements per group
* @return An iterator producing ${coll}s of size `size`, except the
* last will be less than size `size` if the elements don't divide evenly.
*/
def grouped(size: Int): Iterator[C] =
iterator.grouped(size).map(fromSpecific)
I don't see anything related to the order there, so my question is, is this function guaranteed to always return the list of lists in order? E.g. for a batch size of 2:
List(1, 2, 3, 4, 5) returns List(List(1, 2), List(3, 4), List(5))
Any help would be greatly appreciated.
The simple answer is yes, this is guaranteed. The documentation may not be 100% clear (though it is arguably intrinsic to the definition of an Iterator
for an ordered collection), but this ordering is assumed by a large amount of code so this behaviour is never going to change.
Note that the grouped
method is a degenerate case of the sliding
method where the step
and size
are the same.
def grouped[T](list: List[T], size: Int) = list.sliding(size, size)
It makes even less sense for sliding
to deliver results out of order, and in practice they are implemented using the same underlying mechanism.