Java Utility Library

Java Collections - shuffle() Method



The java.util.Collections.shuffle() method is used to randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

Syntax

public static void shuffle(List<?> list)

Parameters

list Specify the list to be shuffled.

Return Value

void type.

Exception

Throws UnsupportedOperationException, if the specified list or its list-iterator does not support the set operation.

Example:

In the example below, the java.util.Collections.shuffle() method is used to shuffle the elements of the given list using default source of randomness.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list objects
    List<Integer> MyList = new ArrayList<Integer>();

    //populating MyList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 

    //shuffle the elements of the list
    Collections.shuffle(MyList);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 
  }
}

The one of the possible outcome of the above code could be:

MyList contains: [10, 20, 30, 40, 50]
MyList contains: [20, 40, 10, 30, 50]

❮ Java.util - Collections