Roohi Bharti
Roohi Bharti

Reputation: 45

Scala Hash Maps

How can we select a random key value pair from a hash map in scala? I have a map of following description

var map = scala.collection.mutable.Map[(Int,Int),ActorRef]()
val random = new Random();
var keys:List[Set(Int,Int)] = map.keySet;
var randomKey:(Int,Int) = keys.get( random.nextInt(keys.size()));
var value= map.get(randomKey);

Upvotes: 1

Views: 376

Answers (2)

sanfann
sanfann

Reputation: 51

val pair = map.toIndexedSeq(Random.nextInt(map.size))

Upvotes: 1

richj
richj

Reputation: 7529

Here is an example that compiles and runs:

import akka.actor.ActorRef
import scala.util.Random

import scala.collection.mutable.{Map => MutableMap}

object RandomMap {

  def main(args: Array[String]): Unit = {
    val map:       MutableMap[(Int, Int), ActorRef] = MutableMap[(Int, Int), ActorRef]((9, 5) -> null, ((15, 1), null))
    val random:    Random                           = new Random()
    val keys:      List[(Int, Int)]                 = map.keySet.toList
    val randomInt: Int                              = random.nextInt(keys.size)
    val randomKey: (Int, Int)                       = keys(randomInt)
    val value:     Option[ActorRef]                 = map.get(randomKey)

    println(s"Random key: $randomKey -> $value")
  }
}

Upvotes: 0

Related Questions