Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly select an item from a list

How can I randomly select an item from a list in Java? e.g. I have

List<String> list = new ArrayList<String>(); list.add("One"); list.add("Two"); 

etc.... How can I randomly select from this list using the

Random myRandomizer = new Random(); 
like image 620
JosephG Avatar asked Sep 19 '12 02:09

JosephG


People also ask

How do I randomly select an item from a list in Excel?

To get a random value from a table or list in Excel, you can use the INDEX function with help from the RANDBETWEEN and ROWS functions. Note: this formula uses the named range "data" (B5:E104) for readability and convenience. If you don't want to use a named range, substitute $B$5:$E$104 instead.

How do I randomly select from a list in Python?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you randomly select 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.


2 Answers

Something like this?

Random randomizer = new Random(); String random = list.get(randomizer.nextInt(list.size())); 
like image 128
Jon Lin Avatar answered Oct 02 '22 15:10

Jon Lin


Clean Code:

List<String> list = new ArrayList<String>(); list.add("One"); list.add("Two"); String random = list.get(new Random().nextInt(list.size())); 
like image 39
user2763281 Avatar answered Oct 02 '22 17:10

user2763281