有没有办法在Java中随机获取HashMap的值? [英] Is there a way to get the value of a HashMap randomly in Java?

查看:3151
本文介绍了有没有办法在Java中随机获取HashMap的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Java中随机获取HashMap的值?

Is there a way to get the value of a HashMap randomly in Java?

推荐答案

/ p>

You could use something like:

Random generator = new Random();
Map.Entry[] entries = myHashMap.entrySet().toArray();
randomValue = entries[generator.nextInt(entries.length)].getValue();

更新。

上述无效 Set.toArray()总是返回 Object s,它不能被强制转换为 Map.Entry 的数组。

The above doesn't work, Set.toArray() always returns an array of Objects, which can't be coerced into an array of Map.Entry.

简单版本)工作:

Random generator = new Random();
Object[] values = myHashMap.values().toArray();
Object randomValue = values[generator.nextInt(values.length)];

如果您希望随机值是 / code>只需添加一个转换到最后一行。因此,如果 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)];

这篇关于有没有办法在Java中随机获取HashMap的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆