Shuffle method is to permute passed list with default or specified randomness.
Syntax
1 2 3 4 5 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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.
1 2 3 4 5 6 7 |
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.