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()
}
}
CodePudding user response:
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()