The union() extension function in Kotlin returns a set containing all distinct elements from both collections.
The syntax of Set.union() extension function is:
infix fun <T> Set<T>.union(other: Iterable<T>): Set<T>
This union() extension function of Set returns a set containing all distinct elements from both collections.
Parameter | Optional/Required | Description |
---|---|---|
other | required | The other collection whose elements are to be included in the union. |
Set.union() returns value of type Set
.
Using union() to find the union of two sets of integers.
For example,
fun main() {
val set1 = setOf(1, 2, 3)
val set2 = setOf(3, 4, 5)
val unionSet = set1 union set2
println(unionSet)
}
[1, 2, 3, 4, 5]
Using union() to find the union of two sets of strings.
For example,
fun main() {
val set1 = setOf("one", "two", "three")
val set2 = setOf("three", "four", "five")
val unionSet = set1 union set2
println(unionSet)
}
[one, two, three, four, five]
Using union() to find the union of two sets of custom objects.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val set1 = setOf(Person("Alice", 30), Person("Bob", 25))
val set2 = setOf(Person("Bob", 25), Person("Charlie", 35))
val unionSet = set1 union set2
println(unionSet)
}
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about union() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.