Pick random element from Set


 

Pick random element from Set

In this section, you will learn how to pick an element randomly from the elements of a Set.

In this section, you will learn how to pick an element randomly from the elements of a Set.

Pick random element from Set

A Set is a collection that contains no duplicate elements. It does not contain duplicate elements This interface models the mathematical set abstraction. Here, we are going to pick an element randomly from the elements of Set. For this, we have added five integer elements to the collection. An object of Random class is created to retrieve any element from the Set. The for loop displays the random element five times and Thread.sleep() method display them one by one after some interval of time.

Here is the code:

import java.util.*;

class PickRandomFromSet {
	public static void main(String[] args) throws Exception {
		Set set = new HashSet();
		set.add(10);
		set.add(20);
		set.add(30);
		set.add(40);
		set.add(50);

		Random rand = new Random();
		for (int i = 0; i < 5; i++) {
			Thread.sleep(5000);
			System.out.println(set.toArray()[rand.nextInt(set.size())]);
		}
	}
}

As we have retrieved the elements randomly, therefore every time they may differ but should always be from the collection elements.

20
20
50
50
20

Ads