Home > Enterprise >  KOTLIN Find Match Between 2 Lists
KOTLIN Find Match Between 2 Lists

Time:02-03

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

CodePudding user response:

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.

CodePudding user response:

I add some comment between the codes. If you have any question, please comment.

        // 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)
            }
        }
  •  Tags:  
  • Related