Skip to main content

How to find the intersection of two HashSets in Kotlin

How to find the intersection of two HashSets in Kotlin.

Here is a step-by-step tutorial on how to find the intersection of two HashSets in Kotlin:

Step 1: Create two HashSets

Before we can find the intersection of two HashSets, we need to create the HashSets themselves. In Kotlin, you can create a HashSet using the mutableSetOf() function. Let's create two HashSets named set1 and set2:

val set1 = mutableSetOf("apple", "banana", "orange", "grape")
val set2 = mutableSetOf("orange", "grape", "kiwi", "pineapple")

Step 2: Find the intersection using the retainAll() function

The retainAll() function is used to find the intersection of two sets. It modifies the original set to keep only the elements that are also present in the other set. In our case, we will use it to find the elements that are common to both set1 and set2.

set1.retainAll(set2)

After this operation, set1 will only contain the elements that are present in both set1 and set2.

Step 3: Print the intersection

To verify that the intersection is correctly found, let's print the elements present in set1 after finding the intersection:

println("Intersection: $set1")

The resulting output should display the elements that are common to both sets.

Complete example: Putting it all together, here's the complete example:

fun main() {
val set1 = mutableSetOf("apple", "banana", "orange", "grape")
val set2 = mutableSetOf("orange", "grape", "kiwi", "pineapple")

set1.retainAll(set2)

println("Intersection: $set1")
}

This program will output:

Intersection: [orange, grape]

That's it! You have successfully found the intersection of two HashSets in Kotlin.