How to display random data from ArrayList in Kotlin?

0

Issue

I have a list of apps installed on the device. Now I want to show a list of 10-20 (the number of applications should always be different) random applications, how can I do this in Kotlin?

My code:

private fun onGetApps() {
        val pm: PackageManager = requireContext().packageManager
        val apps: List<PackageInfo> = requireContext().packageManager.getInstalledPackages(PackageManager.GET_META_DATA)
        val res: ArrayList<Apps> = ArrayList<Apps>()

        for (i in apps.indices) {

            if (pm.getLaunchIntentForPackage (apps[i].packageName) != null)
            {
                val p = apps[i]

                val appInfo = Apps()

                appInfo.appName = p.applicationInfo.loadLabel(requireContext().packageManager).toString()
                appInfo.appImage = p.applicationInfo.loadIcon(requireContext().packageManager)
                res.add(appInfo)
            }

            mAdapter.setupApps(res)
            mAdapter.notifyDataSetChanged()
        }
    }

Solution

One way to do this is to shuffle elements randomly and take first n of them:

println((0..10).shuffled().take(3))

If the number of all items is much bigger than the number of items to take then it probably makes sense to use a sequence:

println((0..10).asSequence().shuffled().take(3).toList())

Note that in the case the number of items to get is bigger than the number of all items, it will return all items in the source collection.

In your case it will be something like:

val res = apps.asSequence()
    .filter { pm.getLaunchIntentForPackage(it.packageName) != null }
    .shuffled()
    .take((10..20).random())
    .map { p ->
        val appInfo = Apps()

        appInfo.appName = p.applicationInfo.loadLabel(requireContext().packageManager).toString()
        appInfo.appImage = p.applicationInfo.loadIcon(requireContext().packageManager)
        
        appInfo
    }.toList()

Answered By – broot

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More