Conditionally Split a List in Kotlin
This article explores different ways to conditionally split a list in Kotlin.
1. Using partition() function
We can use the partition() function to split a list into two, where the first list contains elements for which the specified predicate returned true, and while the second list contains the remaining elements for which the predicate returned false.
|
1 2 3 4 5 6 |
fun main() { val nums = (1..10).toList() val partition = nums.partition { it % 2 == 0 }.toList() println(partition) } |
Output:
[[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
2. Using groupBy() function
Alternately, we can use the groupBy() function to group the elements of the list by a key and get a map with values as the list of corresponding elements. The key is returned by the specified function applied to each element.
|
1 2 3 4 5 6 |
fun main() { val nums = (1..10).toList() val partition = nums.groupBy { it % 2 == 0 }.values println(partition) } |
Output:
[[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
3. Using filter() function
Finally, we can split a list using the filter() function. This results in two separate lists, and not a list of lists, where each list consists of elements that match with the specified predicate.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val nums = (1..10).toList() val odd = nums.filter { it % 2 == 0 } val even = nums.filter { it % 2 == 1 } println(odd) println(even) } |
Output:
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
This is equivalent to the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun main() { val nums = (1..10).toList() val odd = mutableListOf<Int>() val even = mutableListOf<Int>() for (num in nums) { if (num % 2 == 0) { odd.add(num) } else { even.add(num) } } println(odd) println(even) } |
Output:
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
That’s all about conditionally splitting a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)