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

2024-11-08 21:07:27
推荐回答(1个)
回答1:

譬如说:
MapString>
map
=
new
HashMapString>();
先拿所有的键:
Integer[]
keys
=
map.keySet().toArray(new
Integer[0]);
然後随机一个键,找出该值:
Random
random
=
new
Random();
Integer
randomKey
=
keys[random.nextInt(keys.length)];
String
randomValue
=
map.get(randomKey);