Using the 'partition' Function for Splitting Collections

The 'partition' function is a useful tool for splitting a collection into two lists based on a given predicate. This can be particularly handy when you need to separate items into categories, such as filtering out valid and invalid entries from a list. The function returns a Pair containing two lists: the first list consists of the elements that match the predicate, and the second list consists of the elements that do not.


val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val (evenNumbers, oddNumbers) = numbers.partition { it % 2 == 0 }

println("Even Numbers: $evenNumbers") // Output: Even Numbers: [2, 4, 6, 8, 10]
println("Odd Numbers: $oddNumbers")   // Output: Odd Numbers: [1, 3, 5, 7, 9]