将列表分成几部分

有一个简单的方法可以将列表分成几部分(也许是lambda)在Kotlin?

例如:

[1, 2, 3, 4, 5, 6] => [[1, 2], [3, 4], [5, 6]] 

给定列表: val list = listOf(1, 2, 3, 4, 5, 6)你可以使用groupBy

 list.groupBy { (it + 1) / 2 }.map { it.value } 

或者如果你的值不是数字,你可以先给它们分配一个索引:

 list.withIndex() .groupBy { it.index / 2 } .map { it.value.map { it.value } } 

或者,如果你想保存一些分配,你可以使用foldIndexed手动多一点 :

 list.foldIndexed(ArrayList>(list.size / 2)) { index, acc, item -> if (index % 2 == 0) { acc.add(ArrayList(2)) } acc.last().add(item) acc } 

从Kotlin 1.2开始,你可以使用Iterable.chunked(size: Int): List> stdlib中的Iterable.chunked(size: Int): List>函数( https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/hunked .html )。