The partition() extension function in Kotlin splits the original collection into a pair of lists: the first list contains elements for which the predicate yielded true, while the second list contains elements for which the predicate yielded false.
The syntax of Set.partition() extension function is:
fun <T> Set<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>>
This partition() extension function of Set splits the original collection into a pair of lists, where the first list contains elements for which the predicate yielded true, while the second list contains elements for which the predicate yielded false.
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element and returns a Boolean indicating whether the element should be in the first list. |
Set.partition() returns value of type Pair
., List
Using partition() to split a set of integers into even and odd numbers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val (even, odd) = numbers.partition { it % 2 == 0 }
println("Even: $even")
println("Odd: $odd")
}
Even: [2, 4, 6] Odd: [1, 3, 5]
Using partition() to split a set of strings into those with length greater than 3 and others.
For example,
fun main() {
val strings = setOf("one", "two", "three", "four")
val (long, short) = strings.partition { it.length > 3 }
println("Long: $long")
println("Short: $short")
}
Long: [three, four] Short: [one, two]
Using partition() to split a set of custom objects into those that meet a certain criteria and those that do not.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val (older, younger) = people.partition { it.age > 30 }
println("Older: $older")
println("Younger: $younger")
}
Older: [Person(name=Charlie, age=35)] Younger: [Person(name=Alice, age=30), Person(name=Bob, age=25)]
In this Kotlin tutorial, we learned about partition() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.