Kotlin Tutorials

Kotlin Set intersect()
Syntax & Examples

Set.intersect() extension function

The intersect() extension function in Kotlin returns a set containing all elements that are contained by both the original set and the specified collection.


Syntax of Set.intersect()

The syntax of Set.intersect() extension function is:

infix fun <T> Set<T>.intersect(other: Iterable<T>): Set<T>

This intersect() extension function of Set returns a set containing all elements that are contained by both this collection and the specified collection.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe collection to be intersected with the original set.

Return Type

Set.intersect() returns value of type Set.



✐ Examples

1 Finding the intersection of two sets

Using intersect() to find the intersection of two sets of integers.

For example,

  1. Create two sets of integers.
  2. Use intersect() to find the common elements between the two sets.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val set1 = setOf(1, 2, 3, 4)
    val set2 = setOf(3, 4, 5, 6)
    val intersection = set1 intersect set2
    println(intersection)
}

Output

[3, 4]

2 Finding the intersection of a set and a list

Using intersect() to find the intersection of a set of strings and a list of strings.

For example,

  1. Create a set of strings and a list of strings.
  2. Use intersect() to find the common elements between the set and the list.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val set = setOf("a", "b", "c")
    val list = listOf("b", "c", "d")
    val intersection = set intersect list
    println(intersection)
}

Output

[b, c]

3 Finding the intersection of sets with custom objects

Using intersect() to find the intersection of two sets of custom objects.

For example,

  1. Create a data class.
  2. Create two sets of custom objects.
  3. Use intersect() to find the common elements between the two sets.
  4. Print the resulting set.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val set1 = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
    val set2 = setOf(Person("Bob", 25), Person("David", 40), Person("Charlie", 35))
    val intersection = set1 intersect set2
    println(intersection)
}

Output

[Person(name=Bob, age=25), Person(name=Charlie, age=35)]

Summary

In this Kotlin tutorial, we learned about intersect() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.