Skip to content

Get Random Elements from Vector in Java Example

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.

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.

Output

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.

Output

3. Using the ThreadLocalRandom class

The ThreadLocalRandom class generates a random number per thread for the multi-threaded environments.

Output

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

About the author

Leave a Reply

Your email address will not be published.