Select a random element from the array, but unique

I have many countries. I want to select 5 random countries from a list of arrays, but I want them to be unique. This is what I still have:

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 these strings when generating random elements?

Edit:

I expressed myself poorly. The problem is that I do not want the string country1, country 2, etc. It was the same ... so I want them to always be different from each other.

Decision:

 Collections.shuffle(Arrays.asList(allCountries)); 
+8
java arrays
source share
1 answer

Shuffle the array, and then cut off the first 5 elements.

This guarantees 5 unique random elements.

+18
source share

All Articles