Is there a way to get the value of a HashMap randomly in Java?
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 map = new HashMap() {
private static final long serialVersionUID = 1L;
{
put("Foo", 1);
put("Bar", 2);
put("Baz", 3);
}
};
System.out.println(randEntryValue(map));
}
static Entry randEntry(Iterator> it, int count) {
int index = (int) (Math.random() * count);
while (index > 0 && it.hasNext()) {
it.next();
index--;
}
return it.next();
}
static Entry randEntry(Set> entries) {
return randEntry(entries.iterator(), entries.size());
}
static Entry randEntry(Map map) {
return randEntry(map.entrySet());
}
static K randEntryKey(Map map) {
return randEntry(map).getKey();
}
static V randEntryValue(Map map) {
return randEntry(map).getValue();
}
}