Kotlin Set partition()
Syntax & Examples
Set.partition() extension function
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.
Syntax of Set.partition()
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.
Parameters
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. |
Return Type
Set.partition() returns value of type Pair
., List
✐ Examples
1 Partitioning a set of integers into even and odd numbers
Using partition() to split a set of integers into even and odd numbers.
For example,
- Create a set of integers.
- Use partition() with a predicate that checks if the number is even.
- Print the resulting pair of lists.
Kotlin Program
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")
}
Output
Even: [2, 4, 6] Odd: [1, 3, 5]
2 Partitioning a set of strings into those with length greater than 3 and others
Using partition() to split a set of strings into those with length greater than 3 and others.
For example,
- Create a set of strings.
- Use partition() with a predicate that checks if the length of the string is greater than 3.
- Print the resulting pair of lists.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three", "four")
val (long, short) = strings.partition { it.length > 3 }
println("Long: $long")
println("Short: $short")
}
Output
Long: [three, four] Short: [one, two]
3 Partitioning a set of custom objects based on a property
Using partition() to split a set of custom objects into those that meet a certain criteria and those that do not.
For example,
- Create a data class.
- Create a set of custom objects.
- Use partition() with a predicate that checks if the age property is greater than 30.
- Print the resulting pair of lists.
Kotlin Program
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")
}
Output
Older: [Person(name=Charlie, age=35)] Younger: [Person(name=Alice, age=30), Person(name=Bob, age=25)]
Summary
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.