What is "partition()" method in Kotlin?
Kotlin is a versatile and modern programming language that offers a wide range of powerful functions for Android app development and many Java Virtual Machine (JVM) apps.
The partition() method
The partition() function divides a collection into two lists depending on a criterion. It is useful to split collection components into groups based on a certain condition. It efficiently processes the collection only once rather than manually iterating and filtering elements.
Syntax
Here is the syntax of the partition() method:
fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>>
Trepresents the type of elements in the collection.predicaterepresents a lambda function that defines the condition for partitioning.
Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.
Code
Let's look at the code that implements the method partition() given below.
Suppose you have a list of integers and want to partition them into even and odd numbers.
fun main() {val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)val (even, odd) = numbers.partition { it % 2 == 0 }println("Even numbers: $even")println("Odd numbers: $odd")}
Code explanation
Line 1–2: Firstly, we define a list
numbersthat contains integers from 1 to 10.Line 4: Next, we define two variables
evenandodd. Here, we apply thepartition()method to divide the list into two separate lists. We use the modulo operator in the lambda function to check the numbers divisible by 2.Line 6–7: Finally, we print the resulting numbers divisible by 2 in the
evenvariable, and the non-divisible numbers in theoddvariable.
Output
Upon execution, the code will separate the original list of numbers into two separate lists, one with even numbers and one with odd numbers.
The output of the code looks like this:
Even numbers: [2, 4, 6, 8, 10]Odd numbers: [1, 3, 5, 7, 9]
Conclusion
Therefore, the partition() method in Kotlin provides a convenient way to segregate collection elements based on a criterion. The developers working with lists, sets, or other data structures employ this method to divide the data into distinct groups, improving the structure and clarity of the code for their Kotlin application.
Free Resources