Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick a random item from a arraylist in java? [duplicate]

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()));
like image 244
Adam Avatar asked Dec 01 '22 18:12

Adam


1 Answers

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.

like image 52
user253751 Avatar answered Dec 04 '22 11:12

user253751