Kotlin List intersect()
Syntax & Examples
Syntax of List.intersect()
The syntax of List.intersect() extension function is:
infix fun <T> Iterable<T>.intersect( other: Iterable<T> ): Set<T>
This intersect() extension function of List returns a set containing all elements that are contained by both this collection and the specified collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the strings'a', 'p', 'p', 'l', 'e'
. - We also create another list named
list2
containing the strings'p', 'l'
. - We use the
intersect
function to find the common elements betweenlist1
andlist2
. - The result, which is a set containing the elements
'p'
and'l'
, is stored inresult
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "p", "p", "l", "e");
val list2 = listOf("p", "l");
val result = list1.intersect(list2);
println(result);
}
Output
[p, l]
2 Example
In this example,
- We create a list named
list1
containing the integers10, 20, 30
. - We also create another list named
list2
containing the integers20, 30
. - We use the
intersect
function to find the common elements betweenlist1
andlist2
. - The result, which is a set containing the elements
20
and30
, is stored inresult
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(10, 20, 30);
val list2 = listOf(20, 30);
val result = list1.intersect(list2);
println(result);
}
Output
[20, 30]
3 Example
In this example,
- We create a list named
list1
containing the strings'apple', 'banana', 'cherry'
. - We also create another list named
list2
containing the strings'banana', 'orange'
. - We use the
intersect
function to find the common elements betweenlist1
andlist2
. - The result, which is a set containing the element
'banana'
, is stored inresult
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry");
val list2 = listOf("banana", "orange");
val result = list1.intersect(list2);
println(result);
}
Output
[banana]
Summary
In this Kotlin tutorial, we learned about intersect() extension function of List: the syntax and few working examples with output and detailed explanation for each example.