This example shows how to get random elements from Vector in Java. This example also shows how to get random elements from Vector using Random class, ThreadLocalRandom class, and Math class.
How to get random elements from the Vector in Java?
There are several ways using which we can get random elements from the Java vector object as given below.
1. Using the random method of the Math class
The random
method of the Math class returns a positive double number that is greater than or equal to 0 and less than 1.0.
1 |
public static double random() |
We can use this method to generate a random number between 0 and vector size – 1 and then use that number as an index to get the random element from the vector object as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.Vector; public class VectorGetRandomElements { public static void main(String[] args) { Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); //this will print 3 random elements for( int i=0 ; i < 3; i++ ){ /* * Generate a random number between 0 and * vector size - 1 */ int number = (int) (Math.random() * vNumbers.size()); //get the element at random index System.out.println( vNumbers.get(number) ); } } } |
Output
1 2 3 |
20 10 50 |
2. Using the Random class
Instead of the Math class, we can also use the nextInt
method of the Random class to generate a random number as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); //create new object of the Random class Random random = new Random(); for( int i=0 ; i < 3; i++ ){ int number = random.nextInt( vNumbers.size() ); System.out.println( vNumbers.get(number) ); } |
Output
1 2 3 |
50 10 40 |
3. Using the ThreadLocalRandom class
The ThreadLocalRandom class generates a random number per thread for the multi-threaded environments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); for( int i=0 ; i < 3; i++ ){ int number = ThreadLocalRandom.current().nextInt( vNumbers.size() ); System.out.println( vNumbers.get(number) ); } |
Output
1 2 3 |
50 20 20 |
This example is a part of the Vector in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Vector Documentation