sagar suri
sagar suri

Reputation: 4731

How to shuffle a hashmap in kotlin

I have created a hashmap. Now I want to shuffle the objects in it. We have Collections.shuffle() to shuffle all the elements in a list. How can I do the same in hashmap?

This is my hashmap:

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., at regular intervals. Avoid oily and spicy food to ease your pregnancy symptoms. Plan your food intake and have it as 4-5 light meals every day."
            , "Fluids will help you manage" to "Drink sufficient water and fluids to maintain the retention of water in your body. This will help you control constipation, indigestion, dryness, fatigue, bloating and gas. Avoid alcohol and caffeine drinks which may have serious effects during pregnancy."
            , "Do not miss prenatal supplements" to "Doctors prescribe prenatal vitamin and mineral supplements for the normal growth and development. Do not skip these supplements as they can prevent preterm labour and many serious health concerns in the newborn."
            , "Folic acid is essential" to "During pregnancy, have folic acid (supplement) or folate (natural source of folic acid) to avoid various health problems. They are rich in green leafy vegetables, oranges, avocado etc.")

Upvotes: 2

Views: 1725

Answers (2)

Willi Mentzel
Willi Mentzel

Reputation: 29874

I am assuming that you want a random tip, but not the same one twice until the map is exhausted. For that, you should not alter the map at all. Use a singleton which provides you with random tips like that.

val tips = /*...*/

fun main(args: Array<String>) {
  val (title, text) = TipProvider.next()
  println("$title: $text")
}

object TipProvider {

  var tipPool = mutableListOf<String>()

  fun next(): Pair<String, String> {
      if(tipPool.isEmpty()) {
           // create copy of keys
           tipPool = mutableListOf(*(tips.keys.shuffled().toTypedArray()))
      }

      val nextTipKey = tipPool.first()
      tipPool.remove(nextTipKey)
      return nextTipKey to tips[nextTipKey]!!
  }
}

Upvotes: 2

pwolaq
pwolaq

Reputation: 6381

This code should work:

tips.map { it.key to it.value }.shuffled().toMap()

It converts Map to List, shuffles it and then converts back to Map.

Upvotes: 3

Related Questions