地圖& lt整數,字符串& gtmap = new HashMap & lt整數,字符串& gt();
先拿走所有的鑰匙:
Integer[] keys = map.keySet()。toArray(新整數[0]);
然後隨機選擇壹個鍵來查找值:
Random Random = new Random();
integer random key = keys[random . nextint(keys . length)];
string random value = map . get(random key);
//第壹種:通用,二次取值。
System.out.println("遍歷Map.keySet中的鍵和值:");
for (String key : map.keySet()) {
system . out . println(" key = "+key+" and value = "+map . get(key));
}
//第二個
System.out.println("通過Map.entrySet用叠代器遍歷鍵和值:");
叠代器& lt地圖。Entry & ltString,String & gt& gtit = map.entrySet()。叠代器();
while (it.hasNext()) {
地圖。Entry & ltString,String & gtentry = it . next();
system . out . println(" key = "+entry . getkey()+" and value = "+entry . getvalue());
}