4

How can I pick a random item from a list of items in a array list, for example;

ArrayList<Integer>  mylist= new ArrayList<Integer>();
mylist.add(19);
mylist.add(154);
mylist.add(112);
mylist.add(15);
mylist.add(112);

Currently, I am doing this but because I need to use this over and over again, is there a shorter way of do this?

Random random = new Random();
Integer randomInt = lista.get(rand.nextInt(lista.size()));
Adam
  • 186
  • 1
  • 2
  • 13

2 Answers2

13

You can make a method that picks a random item from any list like this:

static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
    return list.get(rand.nextInt(list.size()));
}

Creating a new Random object each time you want a random number is a bad practice. This only creates one and re-uses it.

Also, you can call it with any type of list - not just ArrayList<Integer>s.

user253751
  • 57,427
  • 7
  • 48
  • 90
6

Simple, put your code in a method like this

Random rand; // Global variable

public static int randomItem(Arraylist<Integer> mylist) {
    rand = new Random(); 
    Integer randomInt = lista.get(rand.nextInt(lista.size()));
    return randomInt;
}

and call it like this in your main method;

int selected = randomItem(mylist);
System.out.println(selected);
  • 2
    You've made `rand` an instance variable, but you're setting it from a `static` method, which won't even compile. Creating a new `Random` every time the method is called is a terrible idea. – David Conrad Mar 03 '15 at 20:57