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);
val pair = map.toIndexedSeq(Random.nextInt(map.size))
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")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.