代码之家  ›  专栏  ›  技术社区  ›  sagar suri

如何在kotlin中从hashmap中随机选取对象

  •  6
  • sagar suri  · 技术社区  · 8 年前

    我想随机挑选一个 (key, value) 来自的对象 hashmap 在里面 kotlin .我有以下内容 散列表 已创建。

    val tips = hashMapOf("Having a balanced diet is the key" to "Have nutritious foods like vegetables and fruits along with legumes, whole wheat, cereals etc."
                , "Fluids will help you manage" to "Drink sufficient water and fluids to maintain the retention of water in your body."
                , "Do not miss prenatal supplements" to "Doctors prescribe prenatal vitamin and mineral supplements for the normal growth and development."
                , "Folic acid is essential" to "During pregnancy, have folic acid (supplement) or folate (natural source of folic acid) to avoid various health problems.")
    

    我想随机获得 (键,值) 对象的 散列表 ?

    2 回复  |  直到 8 年前
        1
  •  8
  •   Raouf Rahiche AbdulMomen عبدالمؤمن    8 年前

    最好的方法是生成一个随机数,然后访问列表中的特定数字

    val random = Random() 
    tips.entries.elementAt(random.nextInt(tips.size))
    

    您还可以执行以下操作(不推荐):

    tips.entries.shuffled().first()
    

    注:

    导入kotlin。集合。洗牌

        2
  •  5
  •   jrtapsell    8 年前

    使用扩展函数

    val tips = hashMapOf("Having a balanced diet is the key" to "Have nutritious foods like vegetables and fruits along with legumes, whole wheat, cereals etc."
            , "Fluids will help you manage" to "Drink sufficient water and fluids to maintain the retention of water in your body."
            , "Do not miss prenatal supplements" to "Doctors prescribe prenatal vitamin and mineral supplements for the normal growth and development."
            , "Folic acid is essential" to "During pregnancy, have folic acid (supplement) or folate (natural source of folic acid) to avoid various health problems.")
    
    val random = Random()
    
    fun <T,U> Map<T,U>.random(): Map.Entry<T,U> = entries.elementAt(random.nextInt(size))
    
    fun main(args: Array<String>) {
        println(tips.random())
    }
    

    这适用于任何地图类型,即使项目已添加到地图中。