Is there a way to get the value of a HashMap rando

2020-01-27 03:19发布

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

11条回答
forever°为你锁心
2楼-- · 2020-01-27 03:50

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 );
}
查看更多
神经病院院长
3楼-- · 2020-01-27 03:53

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) );
查看更多
叼着烟拽天下
4楼-- · 2020-01-27 04:01

I wrote a utility to retrieve a random entry, key, or value from a map, entry set, or iterator.

Since you cannot and should not be able to figure out the size of an iterator (Guava can do this) you will have to overload the randEntry() method to accept a size which should be the length of the entries.

package util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapUtils {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>() {
            private static final long serialVersionUID = 1L;
            {
                put("Foo", 1);
                put("Bar", 2);
                put("Baz", 3);
            }
        };

        System.out.println(randEntryValue(map));
    }

    static <K, V> Entry<K, V> randEntry(Iterator<Entry<K, V>> it, int count) {
        int index = (int) (Math.random() * count);

        while (index > 0 && it.hasNext()) {
            it.next();
            index--;
        }

        return it.next();
    }

    static <K, V> Entry<K, V> randEntry(Set<Entry<K, V>> entries) {
        return randEntry(entries.iterator(), entries.size());
    }

    static <K, V> Entry<K, V> randEntry(Map<K, V> map) {
        return randEntry(map.entrySet());
    }

    static <K, V> K randEntryKey(Map<K, V> map) {
        return randEntry(map).getKey();
    }

    static <K, V> V randEntryValue(Map<K, V> map) {
        return randEntry(map).getValue();
    }
}
查看更多
手持菜刀,她持情操
5楼-- · 2020-01-27 04:03

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();
查看更多
家丑人穷心不美
6楼-- · 2020-01-27 04:03

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.

查看更多
smile是对你的礼貌
7楼-- · 2020-01-27 04:05

It depends on what your key is - the nature of a hashmap doesn't allow for this to happen easily.

The way I can think of off the top of my head is to select a random number between 1 and the size of the hashmap, and then start iterating over it, maintaining a count as you go - when count is equal to that random number you chose, that is your random element.

查看更多
登录 后发表回答