Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random string from string array list

Tags:

java

android

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();
like image 758
Badr Hari Avatar asked Jul 17 '11 21:07

Badr Hari


People also ask

How do I return a random element from a list in Java?

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.

Can you randomize strings in Java?

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().


1 Answers

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

like image 152
Jimale Abdi Avatar answered Oct 08 '22 13:10

Jimale Abdi