# Best way to pick a random subset from a collection

I have a large ArrayList and I would like to generate a random subset list of four, without repeats.  I was wondering what the best way to do this would be in Java

Thanks in advance!
Asked:
###### Who is Participating?

Commented:
If you don't want to mess up the initial array, I would generate a list of indexes and do the first four iterations of the standard shuffle algorithm. Then the first four positions of the index array would be your items.

This is the standard shuffle algorithm that I use (where there are N items in the list)
``````int temp;
for (int i = 0; i < N; i++)
{
index = RandBetween(i, N-1);
//swap them
temp = array[i];
array[i] = array[index];
array[index] = temp;
swaper(array, i, index);
}

int RandBetween(int Min, int Max)
{
return Min + (int)(Math.random() * ((Max - Min) + 1))
}
``````

Forgive the c++ syntax. I think this is mostly the same as the way you would do it in Java.

Note that you don't need to go all the way to N. You can just go to 4.
You can see that you might swap item 0 with item 0 etc. This is fine. This algorithm gives equal chance of every possible combination.
0

Commented:
Out of interest - why does it need to be 'random', is there some sort of security angle involved?
0

Commented:
0

Author Commented:
ah well the application I am developing is using the google places API, which will return different results based on different criteria.  However, my application only displays a subset of the places generated.  That subset is supposed to change every time the application is loaded.  It may be difficult to explain without going into a lot of details.
0

Commented:
0

Author Commented:
I implemented something similar to this.  Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Already a member? Login.

All Courses

From novice to tech pro — start learning today.