Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,656 questions

55,403 answers

573 users

How to pick a random value from a map in Scala

1 Answer

0 votes
import scala.util.Random

object RandomPicker {
  def getRandomValue(inputMap: Map[Int, String]): String = {
    val values = inputMap.values.toVector
    val randomIndex = Random.nextInt(values.length)
    
    values(randomIndex)
  }

  def main(args: Array[String]): Unit = {
    val myMap = Map(
      1 -> "C++",
      2 -> "C",
      3 -> "Java",
      4 -> "C#",
      5 -> "Scala",
      6 -> "Python"
    )

    val randomValue = getRandomValue(myMap)
    println(s"Random value: $randomValue")
  }
}
 
 
 
/*
run:
 
Random value: Python
 
*/
 

 



answered Jul 17, 2025 by avibootz

Related questions

3 answers 137 views
1 answer 134 views
1 answer 112 views
3 answers 159 views
3 answers 281 views
...