Find common items in two lists in Kotlin
This article explores different ways to find the common items in two lists in Kotlin, where the returned collection preserves the iteration order of elements in the first list.
1. Using intersect() function
The intersect() function returns a set containing all elements that are contained in both the first list and the second list. Here’s what the code would look like:
|
1 2 3 4 5 6 7 |
fun main() { val first = listOf(1, 3, 1, 6, 5, 7) val second = listOf(2, 3, 4, 5) val common = first.intersect(second) println(common) // [3, 5] } |
2. Using retainAll() function
Alternatively, you can use the retainAll() library function to remove elements from the first list that are missing in the second list. The following solution transforms the first list into a set to avoid any modifications to it, and then calls the retainAll() function on it to retain only the elements that are contained in the second list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T> findCommon(first: List<T>, second: List<T>): Set<T> { val common = first.toMutableSet(); common.retainAll(second) return common } fun main() { val first = listOf(1, 3, 1, 6, 5, 7) val second = listOf(2, 3, 4, 5) val common = findCommon(first, second) println(common) // [3, 5] } |
3. Using filter() function
The idea here is to filter the elements that are contained in the second list. This can be easily done using the filter() function with the contains() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> findCommon(first: List<T>, second: List<T>): Set<T> { return first.filter(second::contains).toSet() } fun main() { val first = listOf(1, 3, 1, 6, 5, 7, 3) val second = listOf(2, 3, 4, 5, 3) val common = findCommon(first, second) println(common) // [3, 5] } |
That’s all about finding the common items in given lists in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)