select random element from arraylist java code example

Example 1: select a random element from a list java

Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));

Example 2: random item from arraylist

ArrayList<Type> arraylistName = new ArrayList<>();

// add items to arraylist
arraylistName.add(item1);
arraylistName.add(item2);
arraylistName.add(item3);

Random random = new Random();
// random index between 0 and arraylistName.size();
int randomIndex = random.nextInt(arraylistName.size());

System.out.println(arraylistName.get(randomIndex));

Tags:

Java Example