Skip to content

Get Random Elements from LinkedHashSet in Java Example

This example shows how to get random elements from LinkedHashSet in Java. This example also shows how to get random elements from LinkedHashSet using an iterator, for loop, and array.

How to get random elements from LinkedHashSet in Java?

There are various ways using which we can get the random elements from the LinkedHashSet as given below.

1. Using the for loop and Random class

We will first generate a random number between 0 and LinkedHashSet size using the nextInt method of the Random class. Once we get the number, we will iterate the LinkedHashSet elements using the enhanced for loop (or an iterator). When we reach the index that is equal to the random number we generated, we will return the element.


2. Using an array

We can also convert the LinkedHashSet to an array and get the random element from the array using the random number generated using the Random class as given below.


3. Using a List

Instead of converting to an array, we can also convert LinkedHashSet to ArrayList (or LinkedList) and get the element at the random index using the get method as given below.


Important Note:

1. If you want to select large number of random elements from the set, you can optimize the array and List approaches by selecting multiple random elements in a single conversion operation.

2. Converting LinkedHashSet to an array or a List needs to allocate resources for the new object which is a costly operation. It may not perform well especially if the LinkedHashSet has a very large number of elements.

This example is a part of the LinkedHashSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 LinkedHashSet

About the author

Leave a Reply

Your email address will not be published.