/ / Cartes de hachage Scala - scala, hashmap, akka

Cartes de hachage Scala - scala, hashmap, akka

Comment pouvons-nous sélectionner une paire de valeur de clé aléatoire à partir d'une carte de hachage dans scala? J'ai une carte de description suivante

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);

Réponses:

1 pour la réponse № 1
val pair = map.toIndexedSeq(Random.nextInt(map.size))

0 pour la réponse № 2

Voici un exemple qui compile et exécute:

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