Splitting original collection into pair of collections
There are times when you wish that you could just split a list into sublists without going into the for
and while
loops. Kotlin provides you with a function just for this occasion. In this recipe, we will see how to split a list based on some criteria.
Getting ready
I'll be using IntelliJ IDEA for writing and running Kotlin code; you are free to use any IDE that can do the same task.
How to do it…
Kotlin provides a partition
function. According to the documentation of the partition function it does the following:
Splits the original array into a pair of lists, where the first list contains elements for which predicate yielded true, while the second list contains elements for which predicate yielded false.
Let's understand it more clearly by going through this example:
- In this example, we will create a list of numbers, and we want to split this list into two sublists: one having odd numbers and the other having even numbers:
fun main(args: Array...