We are moved to new domain
Click -> www.ehowtonow.com
Sunday, 31 May 2015

How to shuffle the element of collection (List)

Following example shows how to shuffle the element of Collection (List) using Collections.shuffle(list); method in Java.

void java.util.Collections.shuffle(List<?> list)
shuffle

public static void shuffle(List<?> list) 
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.The hedge "approximately" is used in the foregoing description because default source of randomness is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity.This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.

This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place.
Parameters:
    list - the list to be shuffled.
Throws:
    UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation.

Sample Program
ShuffleCollection.java
package com.javatutorialcorner.collection;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ShuffleCollection {

	public static void main(String[] args) {
		String[] nameArray = new String[] { "Spring", "Struts", "Hibernate",
				"Webservice", "SOAP Webservice", "RESTful Webservice" };
		List<String> nameList = Arrays.asList(nameArray);

		System.out.println("*********** Before Shuffle ************");
		for (String name : nameList) {
			System.out.println(name);
		}
		Collections.shuffle(nameList);
		System.out.println("*********** After Shuffle ************");
		
		for (String name : nameList) {
			System.out.println(name);
		}

	}

}

Result
The above code will produce the following output.
*********** Before Shuffle ************
Spring
Struts
Hibernate
Webservice
SOAP Webservice
RESTful Webservice
*********** After Shuffle ************
RESTful Webservice
Spring
SOAP Webservice
Struts
Webservice
Hibernate

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to shuffle the element of collection (List) Rating: 5 Reviewed By: eHowToNow