Kotlin Tutorials

Kotlin Set union()
Syntax & Examples

Set.union() extension function

The union() extension function in Kotlin returns a set containing all distinct elements from both collections.


Syntax of Set.union()

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.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe other collection whose elements are to be included in the union.

Return Type

Set.union() returns value of type Set.



✐ Examples

1 Union of two sets of integers

Using union() to find the union of two sets of integers.

For example,

  1. Create two sets of integers.
  2. Use union() to find the union of the two sets.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val set1 = setOf(1, 2, 3)
    val set2 = setOf(3, 4, 5)
    val unionSet = set1 union set2
    println(unionSet)
}

Output

[1, 2, 3, 4, 5]

2 Union of two sets of strings

Using union() to find the union of two sets of strings.

For example,

  1. Create two sets of strings.
  2. Use union() to find the union of the two sets.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val set1 = setOf("one", "two", "three")
    val set2 = setOf("three", "four", "five")
    val unionSet = set1 union set2
    println(unionSet)
}

Output

[one, two, three, four, five]

3 Union of two sets of custom objects

Using union() to find the union of two sets of custom objects.

For example,

  1. Create a data class.
  2. Create two sets of custom objects.
  3. Use union() to find the union of the two sets.
  4. Print the resulting set.

Kotlin Program

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)
}

Output

[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]

Summary

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.