'KOTLIN Find Match Between 2 Lists

So basically I've 2 lists:

val list = context.packageManager.getInstalledPackages(0);
var listOfAvs: MutableList<String> = arrayListOf(
            "com.app1",
            "com.app2"
)

I want to find common elements between the 2 lists. To make both same kind of list I wrote this code

val listMuted: MutableList<String> = arrayListOf()
        var counter = 0
        for(apks in list)
        {
            listMuted.add(apks.packageName.toString())
}

I can't really figure out how to match common elements between both lists. I'm not here writing the code as I made like tens of different functions trying to do that but all of them failed. Please help I'm since a month trying to achieve it



Solution 1:[1]

There is an intersect function that makes this really easy. You can use map to pull the Strings out of the list of PackageInfo.

val commonItems: Set<String> = list
    .map { it.packageName }
    .intersect(listOfAvs)

If you need them in a list you can call toList() or toMutableList() on this result.

Solution 2:[2]

Working Code with small adjustment, thanks LEE!! :-) appreciate man

 fun fromStackoverflow(context: Context)
{
    val list = context.packageManager.getInstalledPackages(0)
    val listMuted: MutableList<String> = arrayListOf()
    // With each apk
    for (apkPackageName in list) {
        // if there is the same package name at the listOfAvs list
        if (apkPackageName.packageName.toString() in listOfAvs) {
            // Add the apk to the listMuted list
            listMuted.add(apkPackageName.packageName.toString())
            println("FOUND!!!"+apkPackageName.packageName.toString())
        } else {
            println("NO MATCH!!!")
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tenfour04
Solution 2 Mundus Code Ltd