Kotlin List.intersect() Examples

Kotlin List intersect()

The intersect() function in Kotlin is used to find the intersection of two lists, i.e., the common elements between them.

Syntax

The intersect() function takes another list as input and returns a new list containing only the elements that are common between the two lists.

fun <T> Iterable<T>.intersect(other: Iterable<T>): List<T>

Parameters

ParameterDescription
otherAnother list whose elements will be compared with the elements of the original list to find the intersection.

Return Value

The intersect() function returns a new list containing the common elements between the original list and the other list.

Example: Finding Intersection of Lists

This example demonstrates how to use intersect() to find the common elements between two lists.

In this example,

  1. Create two lists of numbers, list1 and list2.
  2. Call intersect() on list1 with list2 as the argument.
  3. The intersect() function returns a new list containing the common elements between list1 and list2.

Kotlin Program

fun main() {
    val list1 = listOf(1, 2, 3, 4, 5)
    val list2 = listOf(3, 4, 5, 6, 7)
    val intersection = list1.intersect(list2)
    println("Intersection of list1 and list2: $intersection")
}

Output

Kotlin List intersect() - Example

Summary

The intersect() function in Kotlin is used for finding the common elements between two lists. In this tutorial, we learned the syntax of intersect() function, and how to use this function, with the help of an example.