Adelin
Adelin

Reputation: 18991

How to group each n-element in Scala together?

I have the following list List(1,2,3,4,5,6,7, ... ) I want a list that is groups each n-elements together. For example, every 2 elements would give List((1,2),(3,4),(5,6),(7,8), .... ) every 3 elemenets List((1,2,3), (4,5,6), (7,8,9)) etc.

Upvotes: 2

Views: 930

Answers (2)

bmateusz
bmateusz

Reputation: 237

You can use the grouped function, like this:

List(1,2,3,4,5,6,7).grouped(3)
result: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7))

Upvotes: 4

Tim
Tim

Reputation: 27366

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

list.grouped(2).toList // List(List(1, 2), List(3, 4), List(5, 6), List(7))

Note that the last entry has only 1 element as there are an odd number of elements in the List

The toList is required because grouped returns an iterator, but in most cases you can just process the iterator directly and don't need to convert back to List.

Upvotes: 7

Related Questions