举个例子:
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());
}