Search code examples
kotlinrandomhashmap

Getting "key" from hashMapOf


I want to get my keys from my hashMapOf but when I tried, my values come as well. How can I get just my keys?

val list = hashMapOf("element1" to "1" , "element2" to "2")
 
val random = Random
list.entries.elementAt(random.nextInt(list.keys.size))

I want to get just my keys from my hashMapOf.


Solution

  • If you want to retrieve only the keys from your map, use this:

    list.keys
    

    If you want one random key from the map, use this:

    list.keys.random()
    

    If you want one random value from the map, use this:

    list.values.random()