當前位置:成語大全網 - 書法字典 - JAVA,如何在Map中隨機取出壹對鍵和值?

JAVA,如何在Map中隨機取出壹對鍵和值?

例如:

地圖& 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());

}