Badr Hari
Badr Hari

Reputation: 8424

Pick random element from array, but unique

I have array of countries. I want to pick 5 random countries from my array list, but I want them to be unique. This is what I have so far:

String allCountries[] = {"Finland", "Latvia", "Poland", "Afghanistan", "Albania", "Algeria"};

String country1 = (allCountries[new Random().nextInt(allCountries.length)]);
String country2 = (allCountries[new Random().nextInt(allCountries.length)]);
String country3 = (allCountries[new Random().nextInt(allCountries.length)]);
String country4 = (allCountries[new Random().nextInt(allCountries.length)]);
String country5 = (allCountries[new Random().nextInt(allCountries.length)]);

What is the best way to compare those strings while generating random elements?

Edit:

I expressed myself bad. The problem I have is that I don't want string country1, country 2 etc. to be same... so I want them to be always different.

Solution:

Collections.shuffle(Arrays.asList(allCountries));

Upvotes: 9

Views: 5702

Answers (1)

alex
alex

Reputation: 490657

Shuffle the array and then slice the first 5 elements.

This will guarantee 5 unique random elements.

Upvotes: 19

Related Questions