Kotlin Array - intersect() Function



The Kotlin array intersect() function creates a new set that contains only the elements present in both the array and the specified collection. This means the function returns the set after intersecting the common elements from two or more arrays or collections.

The returned set preserves the element iteration order of the original collection.

Syntax

Following is the syntax of Kotlin array intersect() function −

fun <T>Array<out T>.intersect(predicate: (T) -> Boolean): Int

Parameters

This function accepts other as parameter which is an Iterable<T>, means it can be any collection (like a list, set, or array) containing elements of type T.

Return value

This function returns a set of type T.

Example 1

Following is the basic example to demonstrate the use of intersect() function −

fun main(args: Array<String>) {
   // arr1 first
   val arr1 = arrayOf(4, 5, 6, 7, 2)
   // arr2 second
   val arr2 = arrayOf(2, 1, 5, 7, 8)
   
   // Convert arrays to lists and then find the intersection
   val res = arr1.toList().intersect(arr2.toList())    
   println("This is the intersection list: $res")
}

Output

On execution of the above code we get the following result −

This is the intersection list: [5, 7, 2]

Example 2

Now, let's see another example. Here, we use the intersect() function to display the common element from two lists −

fun main(args: Array<String>){
   //list first
   var list1 = listOf( 1, 5, 3, 7, 2)
   //list second
   var list2 = listOf(2, 1, 5, 4, 7)
   var res = list1.intersect(list2);
   println("this is Intersection list $res")
}

Output

After execution of the above code we get the following output −

this is Intersection list [1, 5, 7, 2]

Example 3

The below example creates two string array. We then use intersect function to find the common string. We then display the intersected list −

fun main(args: Array<String>) {
   val array1 = arrayOf("tutorialspoint", "India", "tutorix", "Hello")
   val array2 = arrayOf("Hello", "World", "tutorialspoint", "Kotlin")

   // Convert arrays to lists and then find the intersection
   val intersection = array1.toList().intersect(array2.toList())

   println("Array 1: [${array1.joinToString()}]")
   println("Array 2: [${array2.joinToString()}]")
   println("Intersection: [${intersection.joinToString()}]")
}

Output

The above code produce following output −

Array 1: [tutorialspoint, India, tutorix, Hello]
Array 2: [Hello, World, tutorialspoint, Kotlin]
Intersection: [tutorialspoint, Hello]
kotlin_arrays.htm
Advertisements