Home Tutorial Java Core Pick random element from Set

 
 

Pick random element from Set
Posted on: May 1, 2010 at 12:00 AM
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

Related Tags for Pick random element from Set:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.