Getting Random Elements from ArrayList in Java
Generating random numbers from the list have a good utility value
There are various methods to get a random element from the ArrayList:
- Using Math.random()
- Using ArrayList Shuffle
- Using Random class
Method 1: Using Math.random()
public static double random()
This method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.
- Math.random() generates a random value between 0 and 1.
- Multiply this value with the size of ArrayList and take only the integer part of this value.
- Now the number that is generated after performing the above steps can be taken as the index of the ArrayList.
- Use the get() method to return a random element from the ArrayList using the above-generated index.
Note: Each time the Math.random() method is called it generates a new random value however original order of elements in the ArrayList does not get disturbed.
Random Element is :70 Random Element is :25 Random Element is :90 Random Element is :5 Random Element is :70 Random Element is :30 Random Element is :70 Random Element is :10
Method 2: Using ArrayList Shuffle
- Collections.shuffle() method of Java shuffles the order of elements in ArrayList.
- Now we can simply iterate over the ArrayList and return elements as they are in random order now.
Note: The actual ArrayList itself gets shuffled and original ordering is lost.
Random values : 19 5 25 90 10 30 80 70
Method 3: Using Random Class function
- nextInt() method of Random class can be used to generate a random value between 0 and the size of ArrayList.
- Now use this number as an index of the ArrayList.
- Use get () method to return a random element from the ArrayList using number generated from nextInt() method.
Note: The original order of the ArrayList remains the same.
Random Element is :5 Random Element is :10 Random Element is :19 Random Element is :5 Random Element is :30 Random Element is :70 Random Element is :25 Random Element is :90
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.