Mundus Code Ltd
Mundus Code Ltd

Reputation: 11

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

Upvotes: 0

Views: 1862

Answers (3)

Mundus Code Ltd
Mundus Code Ltd

Reputation: 11

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

Upvotes: -1

Tenfour04
Tenfour04

Reputation: 93581

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.

Upvotes: 4

Isaac Lee
Isaac Lee

Reputation: 546

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)
            }
        }

Upvotes: 0

Related Questions