Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting random key and value sets from a Map in Java

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 key and value will be strings, for example myMap.put("Geddy", "Lee").

like image 851
Roberto Avatar asked Mar 29 '12 05:03

Roberto


People also ask

How do you get the value of a key from a HashMap in Java?

HashMap get() Method in Java util. HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

What is use of keySet () in Map?

HashMap. keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them.


1 Answers

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); 
like image 67
synopia Avatar answered Oct 03 '22 11:10

synopia