【问题标题】:How to get the random values from List in java>如何从java中的List中获取随机值>
【发布时间】:2013-11-02 22:43:14
【问题描述】:

这是我的代码,

List<HashMap<ArrayList<String>, ArrayList<ArrayList<String>>>> al = new ArrayList<HashMap<ArrayList<String>, ArrayList<ArrayList<String>>>>();

从上面的列表中我得到如下值:

for (HashMap<ArrayList<String>, ArrayList<ArrayList<String>>> entry : al) {

            for (Entry<ArrayList<String>, ArrayList<ArrayList<String>>> mapEntry : entry
                    .entrySet()) {
                key = mapEntry.getKey();
                value = mapEntry.getValue();
            }

        }

我获取值没有任何问题,我的问题是我需要随机获取值(不是重复值)。我如何随机获取值。请任何人帮助我。

提前致谢。

【问题讨论】:

标签: java random-access


【解决方案1】:

Shuffle 列表然后遍历它。

【讨论】:

    【解决方案2】:

    试试这个:

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("abc", 1);
    map.put("def", 2);
    map.put("ghi", 3);
    
    //Creating a list
    List<Integer> list = new ArrayList<Integer>(map.values());
    
    //Generating a random value
    int index = new Random().nextInt(list.size());
    
    //Result
    Integer value = list.get(index);
    

    【讨论】:

    【解决方案3】:

    简单实用的泛型方法:

    static public <T> T getRandom(List<T> list){
        if(list == null || list.isEmpty()){
            return null;
        }else{
            return list.get(rand.nextInt(list.size()));
        }
    }
    

    【讨论】:

    • 只包含代码块的答案并不总是像编写它们的人所认为的那样一目了然。你能解释一下你的代码是如何回答这个问题的吗?
    【解决方案4】:

    在集合类中使用 shuffle()。它会满足你的需要。

    列表列表=新的 ArrayList(); Collections.shuffle(list);

    【讨论】:

    • List, ArrayList>>> al = new ArrayList, ArrayList>>>(); Collections.shuffle(al);
    • 但我没有得到随机值
    【解决方案5】:

    您可以使用 ThreadLocalRandom。详情请查看http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html

    类似于 Siddh 的建议。

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 2019-03-09
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 2010-12-11
      相关资源
      最近更新 更多