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));
Shuffle the array and then slice the first 5 elements.
This will guarantee 5 unique random elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With