skip to Main Content

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

3

Answers


  1. Chosen as BEST ANSWER

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

  2. 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)
                }
            }
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search