Java Collections shuffle

Shuffle method is to permute passed list with default or specified randomness.


Syntax

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

Example :
Let’s see both the function with the help of example.

package org.arpit.java2blog;

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

public class ShuffleMain {

    public static void main(String[] args)
    {
        List<String> listOfEmployeeNames = Arrays.asList("John","Martin","Mohan","Mary","Tom");

        System.out.println("==========================");
        System.out.println("Before shuffling");

        System.out.println(listOfEmployeeNames);

        Collections.shuffle(listOfEmployeeNames);

        System.out.println("==========================");
        System.out.println("After shuffling");

        System.out.println(listOfEmployeeNames);

        listOfEmployeeNames = Arrays.asList("John","Martin","Mohan","Mary","Tom");
        Collections.shuffle(listOfEmployeeNames, new Random(3));

        System.out.println("==========================");
        System.out.println("After shuffling with randomness of 3");

        System.out.println(listOfEmployeeNames);
    }

}

When you run above program, you will get below output:

==========================
Before shuffling
[John, Martin, Mohan, Mary, Tom]
==========================
After shuffling
[Mohan, Martin, Mary, Tom, John]
==========================
After shuffling with randomness of 3
[Mary, Martin, John, Mohan, Tom]

Internal working of Java collections shuffle

Java Collections shuffle interally does Fisher-Yates shuffle.Here is the implementation of shuffle method provided by JDK.

public static void shuffle(List<?> list, Random rnd) {
    int size = list.size();
    if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--)
            swap(list, i-1, rnd.nextInt(i));
    } else {
        Object arr[] = list.toArray();

        // Shuffle array
        for (int i=size; i>1; i--)
            swap(arr, i-1, rnd.nextInt(i));

        // Dump array back into list
        ListIterator it = list.listIterator();
        for (int i=0; i<arr.length; i++) {
            it.next();
            it.set(arr[i]);
        }
    }
}

Here is implementation of swap method.

private static void swap(Object[] x, int a, int b) {
    Object t = x[a];
    x[a] = x[b];
    x[b] = t;
}

That’s all about Java collections shuffle method.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.