2

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.

user2681425
  • 215
  • 1
  • 4
  • 7

5 Answers5

4

Shuffle the list then iterate over it.

amal
  • 1,369
  • 8
  • 15
1

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);
Siddh
  • 712
  • 4
  • 21
1

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()));
    }
}
Mickey Tin
  • 3,408
  • 10
  • 42
  • 71
  • 1
    Answers that just contain code blocks aren't always as self explanatory as they may seem to the people who wrote them. Can you explain how your code answers the question? – apaul Jul 08 '14 at 00:23
0

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

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

Navin
  • 21
  • 2
0

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.

richa_v
  • 119
  • 1
  • 7