简体   繁体   中英

In Scala how to group consecutive elements in array

Given

scala> val a = (1 to 9).toArray
a: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)

would like to group elements in a in this way,

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

If you want to get groups by 3 elements you could use method grouped :

a.grouped(3).toArray
// Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM