This post originated from an RSS feed registered with Scala Buzz
by Zemian Deng.
Original Post: Scala: breaking/chunking a list into list of list
Feed Title: thebugslayer
Feed URL: http://www.jroller.com/thebugslayer/feed/entries/atom?cat=%2FScala+Programming
Feed Description: Notes on Scala and Sweet web framework
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Zemian Deng
Latest Posts From thebugslayer
Advertisement
Q: Break a list into list of list for certain size.
List(1,2,3,4,5,6).chunk(2) == List(List(1,2), List(3,4), List(5,6))
List(1,2,3,4,5,6).chunk(4) == List(List(1,2,3,4), List(5,6))
A:
class ListHelper[T](ls : List[T]) {
/** @param size The size of each sub list */
def chunk(size : Int) = List.range(0, ls.size, size).map{ i => ls.slice(i, i+size) }
}
object ListHelper {
implicit def list2helper[T](ls : List[T]) = new ListHelper(ls)
}
//test
import ListHelper.list2helper
assert(List(1,2,3,4,5,6).chunk(2) == List(List(1,2), List(3,4), List(5,6)))
assert(List(1,2,3,4,5,6).chunk(4) == List(List(1,2,3,4), List(5,6)))
println("passed")
Notes:
Some prefer the parameter to specify the number of pieces when divided rather than the size of each chunk. Just different variation I guess.
Also, this can be seen as undoing the List.flatMap's work.
You can use above to turn a list into map like this:
//turn a list to map
val m = Map() ++ List(1,2,3,4,5,6).chunk(2).map{ xs => (xs(0), xs(1)) }
println(m) // output: Map(1 -> 2, 3 -> 4, 5 -> 6)
Read: Scala: breaking/chunking a list into list of list