Introduction :
In this tutorial, I will show you how to filter one list using another list. For example, if the first list contains 1,2,3,4,5 and if the second list contains 2,4,6,7 and if we filter the first list based on the second list, it will give 2,4.
Kotlin program :
We will use filter() method to filter out a list :
fun main() {
val firstList = listOf(1,2,3,4,5,6,7,8,9)
val secondList = listOf(2,6,8,10,12)
val finalList = firstList.filter { secondList.contains(it) }
print(finalList)
}
Here, we are filtering out the firstList based on if the current element is in secondList or not. It will print the below output :
[2, 6, 8]
Similar tutorials :
- Kotlin program to find out the average marks of a list of students
- 5 different ways to sort a list in ascending/descending order in Kotlin
- Kotlin find index of first element in an iterable/list
- Kotlin program to find one element in a list of objects
- Kotlin program to convert one comma separated string to list
- Kotlin program to convert one list to string