java.util.Collections.shuffle() Method
Advertisements
Description
The shuffle(List<?>) method is used to randomly permute the specified list using a default source of randomness.
Declaration
Following is the declaration for java.util.Collections.shuffle() method.
public static void shuffle(List<?> list)
Parameters
list-- The list to be shuffled.
Return Value
NA
Exception
UnsupportedOperationException-- Throws if the specified list or its list-iterator does not support the set operation.
Example
The following example shows the usage of java.util.Collections.shuffle()
package com.tutorialspoint;
import java.util.*;
public class CollectionsDemo {
public static void main(String args[]) {
// create array list object
List arrlist = new ArrayList();
// populate the list
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
System.out.println("Initial collection: "+arrlist);
// shuffle the list
Collections.shuffle(arrlist);
System.out.println("Final collection after shuffle: "+arrlist);
}
}
Let us compile and run the above program, this will produce the following result.
Initial collection: [A, B, C] Final collection after shuffle: [C, A, B]