如何在Kotlin中从HashMap随机选取一个键值对对象
在Kotlin中从HashMap随机获取键值对
嘿,要从你已经创建的tips HashMap里随机挑一组键值对其实超简单,Kotlin标准库自带的方法就能搞定,不用自己写复杂的随机逻辑~
核心思路
HashMap的entries属性会返回所有键值对的集合(类型是Set<Map.Entry<String, String>>),直接调用这个集合的random()方法,就能随机拿到其中一个键值对元素。
完整代码示例
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 of the fetus." ) // 直接获取随机键值对 val randomTipEntry = tips.entries.random() // 分别取出键和值使用 val tipTitle = randomTipEntry.key val tipContent = randomTipEntry.value // 输出结果示例 println("今日随机孕期提示:") println("- $tipTitle") println("- $tipContent")
处理空HashMap的安全写法
如果你的HashMap有可能是空的,推荐用randomOrNull()代替random()——前者在集合为空时会返回null,不会抛出异常,这样代码更健壮:
val randomTipEntry = tips.entries.randomOrNull() randomTipEntry?.let { entry -> println("今日随机孕期提示:") println("- ${entry.key}") println("- ${entry.value}") } ?: run { println("提示集合为空,无法获取随机提示哦") }
内容的提问来源于stack exchange,提问作者sagar suri
相关产品推荐
相关产品推荐

