Roberto Roberto - 1 year ago 124
Java Question

Selecting random key and value sets from a Map in Java

While I continue to do my research, I thought I post this question to see if anyone can lead me in the right direction. Basically I want to figure out a way 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 key and value will be strings, for example

myMap.put("Geddy", "Lee")

Sorry I don't have any code or implementation to share. To be honest, I'm new to Map objects but it seems to be pretty comprehensive.

Answer Source
HashMap<String, String> x;

Random       random    = new Random();
List<String> keys      = new ArrayList<String>(x.keySet());
String       randomKey = keys.get( random.nextInt(keys.size()) );
String       value     = x.get(randomKey);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download