Skip to main content

How to find the common elements between two arrays in Kotlin

How to find the common elements between two arrays in Kotlin.

Here's a detailed step-by-step tutorial on how to find the common elements between two arrays in Kotlin.

Step 1: Define the arrays

Start by defining two arrays that you want to compare and find the common elements between. For example, let's define two arrays named "array1" and "array2":

val array1 = arrayOf(1, 2, 3, 4, 5)
val array2 = arrayOf(4, 5, 6, 7, 8)

Step 2: Convert arrays to sets

To find the common elements, it's easier to work with sets as they provide built-in functions for intersection. Convert both arrays to sets using the toSet() function:

val set1 = array1.toSet()
val set2 = array2.toSet()

Step 3: Find the intersection of sets

Now that you have two sets, you can find the common elements by taking the intersection of the sets. Kotlin provides the intersect() function to accomplish this:

val commonElements = set1.intersect(set2)

Step 4: Convert the set back to an array (optional)

If you want the common elements as an array instead of a set, you can convert it back using the toTypedArray() function:

val commonElementsArray = commonElements.toTypedArray()

Step 5: Print the common elements

Finally, you can print the common elements to verify the result using a loop or any other method of your choice. Here's an example using a loop:

for (element in commonElementsArray) {
println(element)
}

This will print the common elements between the two arrays: 4 and 5.

Alternative approach using a loop: If you prefer to use a loop instead of sets, you can iterate through one array and check if each element exists in the other array. Here's an example:

val commonElements = mutableListOf<Int>()

for (element in array1) {
if (array2.contains(element)) {
commonElements.add(element)
}
}

In this approach, you create an empty mutable list named "commonElements". Then, you iterate through the first array and use the contains() function to check if each element exists in the second array. If it does, you add it to the commonElements list.

That's it! You now know how to find the common elements between two arrays in Kotlin using both sets and loops.