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

余生颓废 提交于 2020-08-20 04:56:05

问题


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:


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.



来源:https://stackoverflow.com/questions/24651323/how-can-i-group-the-a-list-into-tuple-grouped-items-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!