EN
Java - get random key value element from hash map
11
points
1. Generate random key value from hash map
import java.util.*;
public class JavaGetRandomKeyValueElementFromMapExample {
public static void printRandomMapKeyValueElement() {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.put("D", 4);
map.put("E", 5);
Set<String> keySet = map.keySet();
List<String> keyList = new ArrayList<>(keySet);
int size = keyList.size();
int randIdx = new Random().nextInt(size);
String randomKey = keyList.get(randIdx);
Integer randomValue = map.get(randomKey);
System.out.println("key: " + randomKey + ", value: " + randomValue);
}
public static void main(String[] args) {
printRandomMapKeyValueElement(); // key: E, value: 5
printRandomMapKeyValueElement(); // key: A, value: 1
printRandomMapKeyValueElement(); // key: D, value: 4
}
}