I have list of countries in my array, I would like to pick random country from the list (using random probably?), but I haven't found out the answer myself...
This is what I have so far:
String[] list = {"Finland", "Russia", "Latvia", "Lithuania", "Poland"};
Random r = new Random();
In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method. The key point here is to remember that you mustn't use an index that exceeds your List's size.
You can also create multiple strings containing just numbers, or characters and can concatenate them later, there are endless possibilities to generate a random string in Java using math. random().
The accepted answers is not working for me the solution worked for me is
List<String> myList = Arrays.asList("A", "B", "C", "D");
Suppose you have this above ArrayList
and you want to randomize it
Random r = new Random();
int randomitem = r.nextInt(myList.size());
String randomElement = myList.get(randomitem);
If you print this randomElement
variable you will get random string from your ArrayList
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