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

前端 未结 1 1728
轮回少年
轮回少年 2021-01-22 22:35

for example how can I convert

val list=(1 to 10).toList

into

List((1,2),(3,4),(5,6),(7,8),(9,10))
1条回答
  •  余生分开走
    2021-01-22 22:58

    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.

    0 讨论(0)
提交回复
热议问题