Retrieving a random item from ArrayList in java

Retrieving a random item from ArrayList in java

To retrieve a random item from an ArrayList in Java, you can follow these steps:

  1. Import the necessary Java classes:

    import java.util.ArrayList; import java.util.Random; 
  2. Create an ArrayList and add elements to it.

  3. Use the Random class to generate a random index within the range of valid indices for the ArrayList.

  4. Retrieve the element at the randomly generated index.

Here's a code example that demonstrates how to retrieve a random item from an ArrayList:

import java.util.ArrayList; import java.util.Random; public class RandomArrayListItem { public static void main(String[] args) { // Create an ArrayList and add elements ArrayList<String> myList = new ArrayList<>(); myList.add("Item 1"); myList.add("Item 2"); myList.add("Item 3"); myList.add("Item 4"); myList.add("Item 5"); // Check if the ArrayList is empty if (!myList.isEmpty()) { // Generate a random index Random random = new Random(); int randomIndex = random.nextInt(myList.size()); // Retrieve the random item String randomItem = myList.get(randomIndex); // Print the random item System.out.println("Random Item: " + randomItem); } else { System.out.println("The ArrayList is empty."); } } } 

In this example:

  • We create an ArrayList called myList and add some items to it.
  • We check if the ArrayList is empty to ensure that there are items to select from.
  • We generate a random index using nextInt(myList.size()), where myList.size() is the upper bound for the random index. This ensures that the generated index falls within the valid range of indices for the ArrayList.
  • We retrieve the element at the random index using myList.get(randomIndex) and print it.

This code will output a random item from the ArrayList each time it is executed.


More Tags

send truthtable openhardwaremonitor azure-storage cpu airflow-scheduler file taxonomy fluentvalidation getlatest

More Java Questions

More General chemistry Calculators

More Geometry Calculators

More Electrochemistry Calculators

More Fitness Calculators