Tuesday, May 16, 2017

Collections.shuffle() in Java with Examples

Collections.shuffle() in Java with Examples

java.util.Collections.shuffle() is a java.util.Collections class method.

// Shuffles mylist

public static void shuffle(List mylist)

This method throws UnsupportedOperationException if the
given list or its list-iterator does not support
the set operation.

Sample Code:

import java.util.ArrayList;
import java.util.Collections;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class CollectionSuffleApp {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

ArrayList<String> mylist =new ArrayList<>();
mylist.add("code");
        mylist.add("quiz");
        mylist.add("geeksforgeeks");
        mylist.add("quiz");
        mylist.add("practice");
        mylist.add("qa");
        System.out.println("Original List : \n" + mylist);
        Collections.shuffle(mylist);
        System.out.println("\nShuffled List : \n" + mylist);
}

}


Output:

 Original List : 
[code, quiz, geeksforgeeks, quiz, practice, qa]

Shuffled List : 
[qa, practice, geeksforgeeks, quiz, code, quiz]



It shuffles a given list using the user provided source of randomness.

// mylist is the list to be shuffled.
// rndm is source of randomness to shuffle the list.

public static void shuffle(List mylist, Random rndm)

It throws  UnsupportedOperationException if the specified list or
its list-iterator does not support the set operation.



Key Points:

This method works by randomly permuting the list elements
Runs in linear time. If the provided list does not implement the RandomAccess interface, like LinkedList and is large, it first copies the list into an array, then shuffles the array copy, and finally copies array back into the list. This makes sure that the time remains linear.
It 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.


1 comment:

Shivam Kumar said...

well explained . thanks for sharing good post . Good arraylist example collection visit
Arraylist example