随机从map中获取key值

方法一:


Map map = new HashMap<>();
map.put(1,"测试1");
map.put(2,"测试2");
map.put(3,"测试3");
Integer [] keys = map.keySet().toArray(new Integer[0]); //将map里的key值取出,并放进数组里
int random = (int) (Math.random()*(keys.length)); //生成随机数
Integer randomKey = keys[random]; //随机取key值
System.out.println(randomKey);   //输出随机的key值


方法二:

Map map = new HashMap<>();  
map.put(1,"测试1");
map.put(2,"测试2");
map.put(3,"测试3");
Integer [] keys = map.keySet().toArray(new Integer[0]); //将map里的key值取出,并放进数组里
Random random = new Random();   //生成随机下标
Integer randomKey = keys[random.nextInt(keys.length)];  //取出随机的key值
System.out.println(randomKey);  //输出随机的key值

你可能感兴趣的:(Java,java)