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.

Download Code

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.

Download Code

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.

Download Code

Output:

[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

 
This is equivalent to the following code:

Download Code

Output:

[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

That’s all about conditionally splitting a list in Kotlin.