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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *