KOTLIN 查找两个列表之间的匹配项

KOTLIN Find Match Between 2 Lists

所以基本上我有 2 个列表:

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

我想找到两个列表之间的共同元素。 为了制作相同类型的列表,我编写了这段代码

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

我真的不知道如何匹配两个列表之间的共同元素。 我不是在这里写代码,因为我做了几十个不同的函数来尝试这样做,但都失败了。 请帮助我一个月以来一直在努力实现它

我在代码之间添加了一些注释。如有任何问题,请评论。

        // Well we have to compare with the packagename, so I changed the list to packageName list
        val list: List<String> =
            application.packageManager.getInstalledPackages(0).map { it.packageName.toString() }
        // There wasn't any change at the listOfAvs list and listMuted list.
        val listOfAvs: MutableList<String> = arrayListOf(
            "com.app1",
            "com.app2"
        )
        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 in listOfAvs) {
                // Add the apk to the listMuted list
                listMuted.add(apkPackageName)
            }
        }

intersect 函数可以让这一切变得非常简单。您可以使用 map 将字符串从 PackageInfo 列表中拉出。

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

如果您在列表中需要它们,您可以在此结果上调用 toList()toMutableList()

工作代码稍作调整,谢谢 LEE!! :-) 感谢男人

 fun fromWhosebug(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!!!")
        }
    }
}