Is there a simple way to divide list into parts (maybe some lambda) in Kotlin?
For example:
[1, 2, 3, 4, 5, 6] => [[1, 2], [3, 4], [5, 6]]
In the above example, we have defined a function to split the list. Using a for loop and range() method, iterate from 0 to the length of the list with the size of chunk as the step. Return the chunks using yield . list_a[i:i+chunk_size] gives each chunk.
We can use list comprehension to split a Python list into chunks. It is an efficient way to encapsulate the operations to make the code easier to understand. The complete example code is given below. range(0, len(test_list), n) returns a range of numbers starting from 0 and ending at len(test_list) with a step of n .
Since Kotlin 1.2 you can use Iterable<T>.chunked(size: Int): List<List<T>>
function from stdlib (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/chunked.html).
Given the list: val list = listOf(1, 2, 3, 4, 5, 6)
you can use groupBy
:
list.groupBy { (it + 1) / 2 }.map { it.value }
Or if your values are not numbers you can first assign an index to them:
list.withIndex() .groupBy { it.index / 2 } .map { it.value.map { it.value } }
Or if you'd like to save some allocations you can go a bit more manual way with foldIndexed:
list.foldIndexed(ArrayList<ArrayList<Int>>(list.size / 2)) { index, acc, item -> if (index % 2 == 0) { acc.add(ArrayList(2)) } acc.last().add(item) acc }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With