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.

3
  • stackoverflow.com/questions/929554/… Commented Oct 24, 2013 at 9:40
  • Do you want random values from HashMap, or you also want those HashMaps to be chosen at random? Commented Oct 24, 2013 at 9:45
  • i need random values from hashmap. Commented Oct 24, 2013 at 9:49

5 Answers 5

4

Shuffle the list then iterate over it.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

It is worked but duplicates are repeated
@user2681425 try this link with no repeats stackoverflow.com/questions/15258063/…
@user2681425 it will help to you
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()));
    }
}

1 Comment

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?
0

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

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

2 Comments

List<HashMap<ArrayList<String>, ArrayList<ArrayList<String>>>> al = new ArrayList<HashMap<ArrayList<String>, ArrayList<ArrayList<String>>>>(); Collections.shuffle(al);
but i am not getting random values
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.