public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
Answer from Chris Dennett on Stack Overflowpublic static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
You can use the Random generator to generate a random index and return the element at that index:
//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];
Is there a smart way to get UNIQUE random elements from a collection in Java?
java - Random element from string array - Stack Overflow
Picking a random item from an array of strings in java - Stack Overflow
Get a random object from a array which is in a JSON file
You can select a random object from an array like this,
const quotes = [{},..];
const quote = quotes[Math.floor(Math.random() * quotes.length)];
Now, quote will contain a random object from the quotes array.
More on reddit.com
Videos
Right now I'm using the Random class, which .nextInt(upperbound) provides me with random integers that can be used to index an ArrayList object. I want to get several random elements and want them to be unique, however.
I can come up with some solutions, but none of them are very elegant. Any ideas?
Edit: current solution is to remove the randomly selected element, but I also have to decrease the upperbound (myList.size() - i ) on each iteration of the for-loop.
I know that Pyhton has a function that picks n unique random elements from a list, is there anything similar in Java?
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)];
}