Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to randomly pick an object from a hashmap in kotlin

Tags:

kotlin

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?

like image 713
sagar suri Avatar asked Apr 08 '18 16:04

sagar suri


People also ask

How do I randomly get an element from an array in Kotlin?

The randomOrNull() method is used to return a random element from the ArrayList. If the list is empty, then null is returned.

How do you access map values in Kotlin?

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 .


1 Answers

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

like image 115
Raouf Rahiche Avatar answered Sep 28 '22 07:09

Raouf Rahiche