Home Tutorial Java Core Pick random element from Set

 
 

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

Related Tags for Pick random element from Set:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 1, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com