JAVA,如何随机取出Map中一对键和值?

如题所述

举个例子:

Map<Integer, String> map = new HashMap<Integer, String>();

先拿所有的键:

Integer[] keys = map.keySet().toArray(new Integer[0]);

然後随机一个键,找出该值:

Random random = new Random();

Integer randomKey = keys[random.nextInt(keys.length)];

String randomValue = map.get(randomKey);

//第一种:普遍使用,二次取值

System.out.println("通过Map.keySet遍历key和value:");

for (String key : map.keySet()) {

System.out.println("key= "+ key + " and value= " + map.get(key));

}

//第二种

System.out.println("通过Map.entrySet使用iterator遍历key和value:");

Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();

while (it.hasNext()) {

Map.Entry<String, String> entry = it.next();

System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-15
比如你map里面有十个键值对,你可以用1-10分别对应代替map里面的十个键,然后随机获取1-10里面的一个数,再对应的得到值
第2个回答  推荐于2017-09-13
譬如说:
Map<Integer, String> map = new HashMap<Integer, String>();

先拿所有的键:
Integer[] keys = map.keySet().toArray(new Integer[0]);

然後随机一个键,找出该值:
Random random = new Random();
Integer randomKey = keys[random.nextInt(keys.length)];
String randomValue = map.get(randomKey);本回答被提问者采纳
第3个回答  2013-10-15
Map 一般的是使用HashMap实现的,HashMap是无序。
如果你不知道具体的键-值对,那么你可以使用 For 循环或者Iterator(迭代器) 直接便利循环,直接输出的内容本身就是无序的。
只要一对,你可以只输出一对即可。
第4个回答  2013-10-15
你循环的时候用一个随机数就可以了三。求采纳
相似回答