How to Partition List in Kotlin: Syntax and Examples
In Kotlin, you can partition a list using the
partition function, which splits the list into two lists based on a condition. It returns a Pair of lists: the first with elements matching the condition, and the second with the rest.Syntax
The partition function takes a lambda condition and returns a Pair of lists. The first list contains elements where the condition is true, and the second list contains elements where the condition is false.
list.partition { condition }: Splits the list based on the condition.- The result is a
Pair.- , List
>
kotlin
val (matching, others) = list.partition { it % 2 == 0 }Example
This example shows how to split a list of numbers into even and odd numbers using partition.
kotlin
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val (even, odd) = numbers.partition { it % 2 == 0 }
println("Even numbers: $even")
println("Odd numbers: $odd")
}Output
Even numbers: [2, 4, 6]
Odd numbers: [1, 3, 5]
Common Pitfalls
One common mistake is expecting partition to modify the original list. It does not; it returns new lists. Another is forgetting that the result is a Pair, so you must unpack it properly.
Also, using filter twice instead of partition is less efficient because it iterates the list twice.
kotlin
fun main() {
val numbers = listOf(1, 2, 3, 4)
// Wrong: expecting original list to change
numbers.partition { it > 2 }
println(numbers) // Still [1, 2, 3, 4]
// Right: unpack the pair
val (greater, smallerOrEqual) = numbers.partition { it > 2 }
println(greater) // [3, 4]
println(smallerOrEqual) // [1, 2]
}Output
[1, 2, 3, 4]
[3, 4]
[1, 2]
Key Takeaways
Use
partition to split a list into two based on a condition in one pass.The result is a
Pair of lists: first with elements matching the condition, second with the rest.Always unpack the
Pair to access the two lists separately.partition does not change the original list; it returns new lists.Using
partition is more efficient than filtering twice.