Kotlin program to filter one list using another list

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 :