简体   繁体   中英

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 :

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.

List list=new ArrayList(); Collections.shuffle(list);

You can use . Check http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html for further details.

Similar to what Siddh has suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM