The intersect() extension function in Kotlin returns a set containing all elements that are contained by both the original set and the specified collection.
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.
Parameter | Optional/Required | Description |
---|---|---|
other | required | The collection to be intersected with the original set. |
Set.intersect() returns value of type Set
.
Using intersect() to find the intersection of two sets of integers.
For example,
fun main() {
val set1 = setOf(1, 2, 3, 4)
val set2 = setOf(3, 4, 5, 6)
val intersection = set1 intersect set2
println(intersection)
}
[3, 4]
Using intersect() to find the intersection of a set of strings and a list of strings.
For example,
fun main() {
val set = setOf("a", "b", "c")
val list = listOf("b", "c", "d")
val intersection = set intersect list
println(intersection)
}
[b, c]
Using intersect() to find the intersection of two sets of custom objects.
For example,
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)
}
[Person(name=Bob, age=25), Person(name=Charlie, age=35)]
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.