Java:从HashMap中的给定键返回随机值 >

问题描述 投票:0回答:1

我正在尝试创建一个方法,该方法将在给定特定键时从散列映射中的字符串列表中返回随机值。这是我的代码如下。 (特别是看看方法“getRandomValue”就像那个有困难的那个)。我的问题是:如何在地图中查找键并从hashmap返回一个随机值?

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class Values {
    private Map<String, List<String>> map;
    private static Random rand = new Random();

public void ValueStore() {
    this.map = new HashMap<String, List<String>>();
}

public boolean containsKey(String key) {
    if(map.containsKey(key)) {
        return true;
    } return false;

}

public void put(String key, List<String> value) {
    map = new HashMap<>();
    map.put(key, value);

}

public String getRandomValue(String key) {
    for (String key1 : map.keySet()) {
        if(map.containsKey(key)) {
        //not sure what to do here  
        }
    }
    return key;

}

}
java list random hashmap
1个回答
1
投票

首先在你的类中创建一个java.util.Random实例作为静态final字段,因为你的getRandomValue(String)方法每次被调用时都需要使用它:

private static final Random RANDOM = new Random();

现在在你的方法中使用它:

public String getRandomValue(String key) {
    List<String> list = map.get(key);
    if (list == null) {
        return null; // or throw an exception
    }
    int randomIndex = RANDOM.nextInt(list.length());
    return list.get(randomIndex);
}

Random.nextInt(int x)方法将返回零(包括)和x(不包括)之间的值,这使得它非常适合选择随机索引(因为List和数组索引始终从零开始)。

© www.soinside.com 2019 - 2024. All rights reserved.