I need to pick few random values from ArrayList
, but values cannot duplicate. With code below i simply pick random values but they can duplicate.
for (int i = 0; i < 5; i++) {
index = random.nextInt(menuItems.size());
HashMap<String, String> urls = new HashMap<String, String>();
urls.put("Value", menuItems.get(index).get(KEY_URL));
randomitems.add(urls);
}
Yes, it is in the nature of randomness that the same number may be given again.
To get rid of that you have to manually check the new random number against previously recieved ones and throw all that you do not want.
If you don't need to keep
menutItems
in a specific order, you can simply shuffle it and take the first 5 items:If you do need to keep
menuItems
as it is, you can make a copy first.I'm answering the title of your question here. I use a
Set
to make sure every number is unique and I don't stop adding numbers until it equals the size I want. Then I convert it to aList
:duplicate your list, so you dont mess up your old list
pick one
so every time you pick one, you cannot pick that one again.