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

前端 未结 13 2015
心在旅途
心在旅途 2020-11-30 03:45

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

相关标签:
13条回答
  • 2020-11-30 04:17

    Should you need to draw futher values from the map without repeating any elements you can put the map into a List and then shuffle it.

    List<Object> valuesList = new ArrayList<Object>(map.values());
    Collections.shuffle( valuesList );
    
    for ( Object obj : valuesList ) {
        System.out.println( obj );
    }
    
    0 讨论(0)
  • 2020-11-30 04:19

    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.

    0 讨论(0)
  • 2020-11-30 04:19

    Here is an example how to use the arrays approach described by Peter Stuifzand, also through the values()-method:

    // Populate the map
    // ...
    
    Object[] keys = map.keySet().toArray();
    Object[] values = map.values().toArray();
    
    Random rand = new Random();
    
    // Get random key (and value, as an example)
    String randKey = keys[ rand.nextInt(keys.length) ];
    String randValue = values[ rand.nextInt(values.length) ];
    
    // Use the random key
    System.out.println( map.get(randKey) );
    
    0 讨论(0)
  • 2020-11-30 04:22

    Converting it to an array and then getting the value is too slow when its in the hot path.

    so get the set (either the key or keyvalue set) and do something like:

        public class SetUtility {
            public static<Type> Type getRandomElementFromSet(final Set<Type> set, Random random) {
            final int index = random.nextInt(set.size());
    
            Iterator<Type> iterator = set.iterator();
    
            for( int i = 0; i < index-1; i++ ) {
                iterator.next();
            }
    
            return iterator.next();
        }
    
    0 讨论(0)
  • 2020-11-30 04:28

    i really don't know why you want to do this... but if it helps, i've created a RandomMap that automatically randomizes the values when you call values(), then the following runnable demo application might do the job...

      package random;
    
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Collections;
      import java.util.HashMap;
      import java.util.Iterator;
      import java.util.List;
      import java.util.Map;
      import java.util.TreeMap;
    
      public class Main {
          public static void main(String[] args) {
              Map hashMap = makeHashMap();
              // you can make any Map random by making them a RandomMap
              // better if you can just create the Map as a RandomMap instead of HashMap
              Map randomMap = new RandomMap(hashMap);
    
              // just call values() and iterate through them, they will be random
              Iterator iter = randomMap.values().iterator();
    
              while (iter.hasNext()) {
                  String value = (String) iter.next();
                  System.out.println(value);
              }
          }
    
          private static Map makeHashMap() {
              Map retVal;
    
              // HashMap is not ordered, and not exactly random (read the javadocs)
              retVal = new HashMap();
    
              // TreeMap sorts your map based on Comparable of keys
              retVal = new TreeMap();
    
              // RandomMap - a map that returns stuff randomly
              // use this, don't have to create RandomMap after function returns
              // retVal = new HashMap();
    
              for (int i = 0; i < 20; i++) {
                  retVal.put("key" + i, "value" + i);
              }
    
              return retVal;
          }
      }
    
      /**
       * An implementation of Map that shuffles the Collection returned by values().
       * Similar approach can be applied to its entrySet() and keySet() methods.
       */
      class RandomMap extends HashMap {
          public RandomMap() {
              super();
          }
    
          public RandomMap(Map map) {
              super(map);
          }
    
          /**
           * Randomize the values on every call to values()
           *
           * @return randomized Collection
           */
          @Override
          public Collection values() {
              List randomList = new ArrayList(super.values());
              Collections.shuffle(randomList);
    
              return randomList;
          }
    
      }
    
    0 讨论(0)
  • 2020-11-30 04:29

    Usually you do not really want a random value but rather just any value, and then it's nice doing this:

    Object selectedObj = null;
    for (Object obj : map.values()) {
        selectedObj = obj;
        break;
    }
    
    0 讨论(0)
提交回复
热议问题