sagar suri
sagar suri

Reputation: 4731

how to randomly pick an object from a hashmap in 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?

Upvotes: 6

Views: 3587

Answers (2)

Raouf Rahiche
Raouf Rahiche

Reputation: 31386

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

Upvotes: 11

jrtapsell
jrtapsell

Reputation: 7031

Using an extension function

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.")

val random = Random()

fun <T,U> Map<T,U>.random(): Map.Entry<T,U> = entries.elementAt(random.nextInt(size))

fun main(args: Array<String>) {
    println(tips.random())
}

This works for any map kind, and even if items are added to the map.

Upvotes: 5

Related Questions