0
0
KotlinHow-ToBeginner · 3 min read

How to Find Intersection of Sets in Kotlin Easily

In Kotlin, you can find the intersection of two sets using the intersect() function. This function returns a new set containing elements common to both sets.
📐

Syntax

The intersect() function is called on one set and takes another set as an argument. It returns a new set with elements that appear in both sets.

  • set1.intersect(set2): Returns a set with common elements.
kotlin
val set1 = setOf(1, 2, 3, 4)
val set2 = setOf(3, 4, 5, 6)
val intersection = set1.intersect(set2)
💻

Example

This example shows how to find the intersection of two sets and print the result.

kotlin
fun main() {
    val set1 = setOf("apple", "banana", "cherry")
    val set2 = setOf("banana", "cherry", "date", "fig")
    val commonFruits = set1.intersect(set2)
    println("Common fruits: $commonFruits")
}
Output
Common fruits: [banana, cherry]
⚠️

Common Pitfalls

One common mistake is trying to use intersect() on mutable sets expecting the original sets to change. intersect() returns a new set and does not modify the original sets.

Also, remember that sets do not keep order, so the result may appear in any order.

kotlin
fun main() {
    val set1 = mutableSetOf(1, 2, 3)
    val set2 = mutableSetOf(2, 3, 4)
    val intersection = set1.intersect(set2)
    println("Intersection: $intersection")
    println("Original set1 after intersect: $set1")
}
Output
Intersection: [2, 3] Original set1 after intersect: [1, 2, 3]
📊

Quick Reference

FunctionDescription
intersect(otherSet)Returns a new set with elements common to both sets.
retainAll(otherSet)Modifies the original mutable set to keep only elements also in otherSet.
setOf(...)Creates an immutable set.
mutableSetOf(...)Creates a mutable set.

Key Takeaways

Use intersect() to get a new set with common elements between two sets.
intersect() does not change the original sets; it returns a new set.
Sets in Kotlin do not guarantee element order in the intersection result.
For mutable sets, use retainAll() to modify the set in place.
Always pass a set or collection as the argument to intersect().