I want to get random keys and their respective values from a Map. The idea is that a random generator would pick a key and display that value. The tricky part is that both k
I would copy the Map into an array and select the entry you want at random. This avoid the need to also lookup the value from the key.
Map x = new HashMap();
Map.Entry[] entries = x.entrySet().toArray(new Map.Entry[0]);
Random rand = new Random();
// call repeatedly
Map.Entry keyValue = entries[rand.nextInt(entries.length)];
If you want to avoid duplication, you can randomize the order of the entries
Map x = new HashMap();
List> entries = new ArrayList> (x.entrySet());
Collections.shuffle(entries);
for (Map.Entry entry : entries) {
System.out.println(entry);
}