Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide list into parts

Tags:

kotlin

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]] 
like image 570
Letfar Avatar asked Nov 19 '16 23:11

Letfar


People also ask

How do you divide a list into parts?

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.

How do you break a list in Python?

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 .


2 Answers

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).

like image 153
VasyaFromRussia Avatar answered Sep 18 '22 18:09

VasyaFromRussia


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 } 
like image 24
miensol Avatar answered Sep 18 '22 18:09

miensol