Java Utility Library

Java Collections - shuffle() Method



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

Syntax

public static void shuffle(List<?> list,
                           Random rnd)

Parameters

list Specify the list to be shuffled.
rnd Specify the source of randomness to use to shuffle the list.

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 specified 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); 

    //creating a random object
    Random rand = new Random();

    //shuffle the elements of the list using
    //source of randomness
    Collections.shuffle(MyList, rand);

    //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: [40, 30, 10, 50, 20]

❮ Java.util - Collections