0
0
KotlinHow-ToBeginner · 3 min read

How to Find Union of Sets in Kotlin: Simple Guide

In Kotlin, you can find the union of two sets using the union() function, which returns a new set containing all distinct elements from both sets. For example, set1.union(set2) combines elements from set1 and set2 without duplicates.
📐

Syntax

The union() function is called on a set and takes another set as an argument. It returns a new set containing all unique elements from both sets.

  • set1.union(set2): Returns a new set with elements from set1 and set2.
kotlin
val set1 = setOf(1, 2, 3)
val set2 = setOf(3, 4, 5)
val unionSet = set1.union(set2)
💻

Example

This example shows how to find the union of two sets and print the result. It demonstrates that duplicates are removed in the union.

kotlin
fun main() {
    val set1 = setOf(1, 2, 3)
    val set2 = setOf(3, 4, 5)
    val unionSet = set1.union(set2)
    println("Union of set1 and set2: $unionSet")
}
Output
Union of set1 and set2: [1, 2, 3, 4, 5]
⚠️

Common Pitfalls

One common mistake is expecting the + operator to modify the original set. Remember, sets in Kotlin are immutable by default, so union() returns a new set without changing the originals.

Also, using union() on lists instead of sets may not remove duplicates as expected.

kotlin
fun main() {
    val set1 = setOf(1, 2, 3)
    val set2 = setOf(3, 4, 5)

    // Using + operator creates a new set
    val unionWithPlus = set1 + set2
    println("Using + operator: $unionWithPlus")

    // Using union() to get a new set
    val unionWithFunction = set1.union(set2)
    println("Using union(): $unionWithFunction")
}
Output
Using + operator: [1, 2, 3, 4, 5] Using union(): [1, 2, 3, 4, 5]
📊

Quick Reference

OperationDescriptionExample
union()Returns a new set with all unique elements from both setsset1.union(set2)
+ operatorCreates a new set combining elements but does not modify original setsset1 + set2
MutableSet.addAll()Adds all elements from another collection to a mutable setmutableSet.addAll(set2)

Key Takeaways

Use the union() function to combine two sets without duplicates in Kotlin.
union() returns a new set and does not modify the original sets.
The + operator can also combine sets but creates a new set without changing originals.
For mutable sets, use addAll() to add elements from another set.
union() works only on sets; using it on lists may not remove duplicates.