Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the value of a HashMap randomly in Java?

Is there a way to get the value of a HashMap randomly in Java?

like image 213
Varuna Avatar asked May 30 '09 11:05

Varuna


People also ask

How do I find the value of a HashMap?

HashMap. containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map.

How do I extract a value from a map?

HashMap get() Method in Java 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.


2 Answers

This works:

Random generator = new Random(); Object[] values = myHashMap.values().toArray(); Object randomValue = values[generator.nextInt(values.length)]; 

If you want the random value to be a type other than an Object simply add a cast to the last line. So if myHashMap was declared as:

Map<Integer,String> myHashMap = new HashMap<Integer,String>(); 

The last line can be:

String randomValue = (String) values[generator.nextInt(value.length)]; 

The below doesn't work, Set.toArray() always returns an array of Objects, which can't be coerced into an array of Map.Entry.

Random generator = new Random(); Map.Entry[] entries = myHashMap.entrySet().toArray(); randomValue = entries[generator.nextInt(entries.length)].getValue(); 
like image 89
Tom Jefferys Avatar answered Sep 19 '22 14:09

Tom Jefferys


Since the requirements only asks for a random value from the HashMap, here's the approach:

  1. The HashMap has a values method which returns a Collection of the values in the map.
  2. The Collection is used to create a List.
  3. The size method is used to find the size of the List, which is used by the Random.nextInt method to get a random index of the List.
  4. Finally, the value is retrieved from the List get method with the random index.

Implementation:

HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("Hello", 10); map.put("Answer", 42);  List<Integer> valuesList = new ArrayList<Integer>(map.values()); int randomIndex = new Random().nextInt(valuesList.size()); Integer randomValue = valuesList.get(randomIndex); 

The nice part about this approach is that all the methods are generic -- there is no need for typecasting.

like image 34
coobird Avatar answered Sep 19 '22 14:09

coobird