有没有办法在 Java 中随机获取 HashMap 的值? [英] Is there a way to get the value of a HashMap randomly in Java?
本文介绍了有没有办法在 Java 中随机获取 HashMap 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 Java 中随机获取 HashMap 的值?
Is there a way to get the value of a HashMap randomly in Java?
推荐答案
这有效:
Random generator = new Random();
Object[] values = myHashMap.values().toArray();
Object randomValue = values[generator.nextInt(values.length)];
如果您希望随机值是 Object
以外的类型,只需在最后一行添加一个强制转换即可.所以如果 myHashMap
被声明为:
If you want the random value to be a type other than an Object
simply add a cast to the last line. So if myHashMap
was declared as:
Map<Integer,String> myHashMap = new HashMap<Integer,String>();
最后一行可以是:
String randomValue = (String) values[generator.nextInt(value.length)];
<小时>
下面的不起作用,Set.toArray()
总是返回一个Object
的数组,不能被强制Map.Entry
的数组.
The below doesn't work, Set.toArray()
always returns an array of Object
s, which can't be coerced into an array of Map.Entry
.
Random generator = new Random();
Map.Entry[] entries = myHashMap.entrySet().toArray();
randomValue = entries[generator.nextInt(entries.length)].getValue();
这篇关于有没有办法在 Java 中随机获取 HashMap 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文