I am trying to randomly pick a (key, value)
object from a hashmap
in kotlin
. I have below hashmap
created.
val tips = hashMapOf("Having a balanced diet is the key" to "Have nutritious foods like vegetables and fruits along with legumes, whole wheat, cereals etc."
, "Fluids will help you manage" to "Drink sufficient water and fluids to maintain the retention of water in your body."
, "Do not miss prenatal supplements" to "Doctors prescribe prenatal vitamin and mineral supplements for the normal growth and development."
, "Folic acid is essential" to "During pregnancy, have folic acid (supplement) or folate (natural source of folic acid) to avoid various health problems.")
I want to randomly get the (key, value)
object from the hashmap
?
The randomOrNull() method is used to return a random element from the ArrayList. If the list is empty, then null is returned.
For retrieving a value from a map, you must provide its key as an argument of the get() function. The shorthand [key] syntax is also supported. If the given key is not found, it returns null .
the best way is by generating a random number and then access that specific number in the list
val random = Random()
tips.entries.elementAt(random.nextInt(tips.size))
You can also do something like (not recommended):
tips.entries.shuffled().first()
NOTE :
import kotlin.collections.shuffled
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With