Random string from string array list

Viewed 55184

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();
8 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

Here's a solution in 1 line:

String country = new String[] {"Finland", "Russia", "Latvia", "Lithuania", "Poland"}[(int)(Math.random()*5)];

import java.util.Random; public static void main (String [] args){

// For this code, we are trying to pic a random day from days

String [] days = {"Sunday","Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"};

Random rand = new Random();

int Rand_item = rand.nextInt(days.length);

System.out.println(days[Rand_item]);

}

Related