Kotlin Array.intersect()

Kotlin Array.intersect() Function

In Kotlin, the Array.intersect() function is used to create a new array containing the distinct elements that are common between the current array and another collection. It returns an array that contains only the elements that exist in both arrays.

This function is particularly useful when you need to find the intersection of elements between two arrays and create a new array with those common elements.

In this tutorial, we’ll explore the syntax of the Array.intersect() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.intersect() function is as follows:

fun <T> Array<out T>.intersect(other: Iterable<T>): Array<T>

The intersect() function takes another iterable collection other as a parameter and returns a new array containing the common elements between the two collections.

Examples for Array.intersect() Function

1. Finding the intersection of two arrays

In this example, we’ll use the intersect() function to find the common elements between two arrays of strings and create a new array with those elements.

Kotlin Program

fun main() {
    val array1 = arrayOf("apple", "orange", "banana", "grape")
    val array2 = arrayOf("orange", "grape", "kiwi", "melon")

    // Using intersect() to find common elements between two arrays
    val commonElements = array1.intersect(array2.toSet())

    // Printing the original arrays and the result
    println("Array 1\n${array1.joinToString(", ")}\n")
    println("Array 2\n${array2.joinToString(", ")}\n")
    println("Common Elements\n${commonElements.joinToString(", ")}")
}

Output

Array 1
apple, orange, banana, grape

Array 2
orange, grape, kiwi, melon

Common Elements
orange, grape

Please observe in the program that we have passed array2.toSet() as argument to the intersect() method, because, intersect() function expects Iterable<TypeVariable(T)>.

Summary

In this tutorial, we’ve covered the intersect() function in Kotlin arrays, its syntax, and how to use it to find and create a new array with the common elements between two arrays.