user2681425
user2681425

Reputation: 215

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.

Upvotes: 2

Views: 5717

Answers (5)

richa_v
richa_v

Reputation: 129

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

Similar to what Siddh has suggested.

Upvotes: 0

Mickey Tin
Mickey Tin

Reputation: 3543

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()));
    }
}

Upvotes: 1

Siddh
Siddh

Reputation: 712

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);

Upvotes: 1

Navin
Navin

Reputation: 21

Use shuffle() in collections class.It will satisfy your need.

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

Upvotes: 0

amal
amal

Reputation: 1369

Shuffle the list then iterate over it.

Upvotes: 4

Related Questions