Pooya
Pooya

Reputation: 4481

How can I group the a list into tuple grouped items in Scala?

for example how can I convert

val list=(1 to 10).toList

into

List((1,2),(3,4),(5,6),(7,8),(9,10))

Upvotes: 2

Views: 528

Answers (1)

ayvango
ayvango

Reputation: 5977

You may use grouped method for the List class: http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List

list.grouped(2).toList.collect { case a :: b :: Nil => (a,b) }
res1: List[(Int, Int)] = List((1,2), (3,4), (5,6), (7,8), (9,10))

collect is used to convert list of lists to list of tuples.

Upvotes: 8

Related Questions