我有一个接受HashMap<String, HashSet<Integer>>
的函数。现在我想从HashMap
获得一个随机值,但我不知道如何做到这一点。你能给我一个暗示吗?
输出应包含一个包含String
和Integer
值的元组。
答案 0 :(得分:2)
知道地图的大小,您可以选择一个随机的条目编号,然后迭代内容,直到您到达该条目。例如:
final Set<String> keys = allowedInput.keySet();
final int keyNumber = (int)(Math.random() * keys.size());
final Iterator<String> keyIterator = keys.iterator();
String randomKey = null;
for (int i = 0; i < keyNumber && keyIterator.hasNext(); i++) {
randomKey = keyIterator.next();
}
if (randomKey == null) {
// This should not happen unless the map was empty, or it was modified
// externally. Handle the potential error case accordingly.
}
final HashSet<Integer> value = allowedInput.get(randomKey);
// `value` now contains a random element from the `allowedInput` map.
如果要从结果Integer
中检索随机HashSet<Integer>
元素,则可以采用相同的技术:只需根据集合的大小选择随机元素编号,然后迭代直到找到它为止。
答案 1 :(得分:1)
如果你想重复获取随机值,你可以随机播放,然后按顺序浏览它。
答案 2 :(得分:1)
我创建了一个利用Mike和SecureRandom的答案的通用解决方案,并包含显式的空值和边界检查,以及单例集合的快速返回(在那里选择不多)。
public static <T> T getRandomElement(Collection<T> collection) {
if (collection == null || collection.isEmpty()) {
throw new IllegalArgumentException("Collection should not be null or empty");
}
if (collection.size() == 1) {
return collection.iterator().next();
}
// it would be beneficial to make this a field when used a lot
final Random random = new SecureRandom();
final int randomIndex = random.nextInt(collection.size());
// optimization for list instances, use optimized indexing
if (collection instanceof List) {
final List<T> list = (List<T>) collection;
return list.get(randomIndex);
}
int seen = 0;
for (T e : collection) {
if (seen++ == randomIndex) {
return e;
}
}
throw new IllegalStateException("Collection size was altered during operation");
}
现在,您只需先从密钥集中选择一个密钥值,然后从该值中选择一个随机整数,就可以直接检索String
和Integer
。
String key = getRandomElement(aMap.keySet());
Integer value = getRandomElement(aMap.get(key));
答案 3 :(得分:0)
final Set<String> keys = allowedInput.keySet();
int keyNumber = (int)(random.nextInt(keys.size()));
final Iterator<String> keyIterator = keys.iterator();
String key = null;
for (int i = 0; i <= keyNumber; i++) {
key = keyIterator.next();
}
if (key == null) {
// handle empty map
}
HashSet<Integer> field = allowedInput.get(key);
final int fieldNumber = (int)(random.nextInt(field.size()));
int fieldID = 0;
int i = 0;
for(Object obj : field)
{
if (i == fieldNumber)
{
//fieldID = Integer.parseInt(obj.toString());
fieldID = (int)obj;
break;
}
i = i + 1;
}
// Start constructing the userinput
// Note: we need an instance of the UserInputSystem to create the UserInput instance!
UserInputSystem userInputSystem = new UserInputSystem();
UserInput input = userInputSystem.new UserInput(fieldID, key);
System.err.println("ai fieldID = "+fieldID+" key = "+key);