Try:
list[r.nextInt(list.length)];
Answer from Burleigh Bear on Stack OverflowTry:
list[r.nextInt(list.length)];
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
HELP - How to get a random string item from list
java - Getting a random String from a List - Stack Overflow
How do I pick a random string from my list.
Picking a random item from an array of strings in java - Stack Overflow
Hello I have a list.
String[] boysNames = {"Bob", "Adam", "Tom", "Brandon"};
What is some code that would pick one string from this list?
Use the Random.nextInt(int) method:
final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};
Random random = new Random();
int index = random.nextInt(proper_noun.length);
System.out.println(proper_noun[index]);
This code is not completely safe: one time out of four it'll choose Richard Nixon.
To quote a documentation Random.nextInt(int):
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
In your case passing an array length to the nextInt will do the trick - you'll get the random array index in the range [0; your_array.length)
if you use List instead of arrays you can create simple generic method which get you random element from any list:
public static <T> T getRandom(List<T> list)
{
Random random = new Random();
return list.get(random.nextInt(list.size()));
}
if you want to stay with arrays, you can still have your generic method, but it will looks bit different
public static <T> T getRandom(T[] list)
{
Random random = new Random();
return list[random.nextInt(list.length)];
}
Pseudocode:
Generate a random integer n between 0 and 9
if (n==0) return "abc"
else if (n <= 6) return "def"
else if (n <= 8) return "ghi"
else return "danny"
There are many ways to do this
Basically, to use probabilities, you generate a random number between 0 and 100, not including the 100.
Then, you test for each of the strings in turn, adding the probabilities:
String s;
if (number < 10) {s = "abc";}
else if (number < 70) { s = "def";}
else if (number < 90) {s = "ghi";}
else {s = "danny";}