[英]How to get the random values from List in java>
Here my code is, 这是我的代码
List<HashMap<ArrayList<String>, ArrayList<ArrayList<String>>>> al = new ArrayList<HashMap<ArrayList<String>, ArrayList<ArrayList<String>>>>();
from above list i am getting values like below: 从上面的列表中,我得到的值如下:
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();
}
}
I am getting values without any problem,Here my problem is i need to get values randomly(not duplicate values).How i can get the values randomly.Please can any one help me. 我正在获取值而没有任何问题,这里我的问题是我需要随机获取值(而不是重复的值)。我如何随机获取值。请有人可以帮助我。
Thanking in Advance. 在此先感谢。
随机播放列表,然后遍历它。
Try this out: 试试看:
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);
Simple util generic method : 简单的util通用方法:
static public <T> T getRandom(List<T> list){
if(list == null || list.isEmpty()){
return null;
}else{
return list.get(rand.nextInt(list.size()));
}
}
Use shuffle() in collections class.It will satisfy your need. 在collections类中使用shuffle(),它将满足您的需求。
List list=new ArrayList(); 列表list = new ArrayList(); Collections.shuffle(list); Collections.shuffle(名单);
You can use ThreadLocalRandom . 您可以使用ThreadLocalRandom 。 Check http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html for further details. 检查http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html了解更多详细信息。
Similar to what Siddh has suggested. 与Siddh的建议相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.