Bob
Bob

Reputation: 8504

Split a big collection into smaller ones

Let's say I have this:

val list = Seq(1,2,3,4,5,6,7)

I would like to transform it into this

Seq[Seq[Int]]

Except that the inner Seq should be of size 2 max, so the final output is something like this

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

Upvotes: 0

Views: 273

Answers (1)

Luigi Plinge
Luigi Plinge

Reputation: 51109

You need the grouped method, which returns an Iterator. You can then call toSeq or toList on the Iterator.

scala> list.grouped(2).toSeq
res14: Seq[Seq[Int]] = Stream(List(1, 2), ?)

Upvotes: 4

Related Questions