How to Shuffle the Elements of Array in Java?
Last Updated :
25 Nov, 2024
In Java, to shuffle the elements of an array, we can use the shuffle()
method from the Collections
class. This method is part of the java.util
package. To shuffle an array, first, we need to convert the array into a List
, shuffle it, and then convert it back to an array if needed.
Example:
Let's go through the below example to shuffle an array using the basic shuffle() method of the Collection class.
Java
// Java Program to shuffle the
// elements of an array
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayShuffle {
public static void main(String[] args) {
Integer[] arr = {1, 2, 3, 4,};
// Convert array to list
List<Integer> l = Arrays.asList(arr);
// Shuffle the list
Collections.shuffle(l);
// Convert list back to array (if needed)
arr = l.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));
}
}
Note: shuffle( ) Method only works with Lists, you may need to convert primitive arrays like int[] to Integer[ ] or another wrapper class array before you can shuffle them.
Syntax of shuffle() Method
public static void shuffle(List<?> list)
- Parameter:
list
: A List<?>
(a list of any type of elements). - Return Type: This method does not return anything.
Other Ways to Shuffle the Elements of an Array in Java
Using Fisher-Yates Shuffle Algorithm
The Fisher-Yates algorithm is an efficient way to shuffle an array in random order. It works by iterating over the array and swapping each element with a random element that comes after it (including itself).
Java
// Java Program to Shuffle the
// elements of an array
// using Fisher-Yates Shuffle Algorithm
import java.util.*;
public class FisherYatesAlgo {
public static void main(String[] args) {
Integer[] arr = {1, 2, 3, 4,};
// Fisher-Yates Shuffle Algorithm
Random r = new Random();
for (int i = arr.length - 1; i > 0; i--) {
// Random index from 0 to i
int j = r.nextInt(i + 1);
// Swap elements at i and j
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
System.out.println("" + Arrays.toString(arr));
}
}
Shuffle Array Containing Characters
Shuffling an array of characters is similar to shuffling any other type of array. We can use the Fisher-Yates algorithm or shuffle() methods mentioned earlier to shuffle an array of characters.
Java
// Java Program to Shuffle Array
// Containing Characters
import java.util.*;
public class ShuffleCharacter {
public static void main(String[] args) {
char[] arr = {'A', 'B', 'C', 'D',};
// Fisher-Yates Shuffle for Characters
Random r = new Random();
for (int i = arr.length - 1; i > 0; i--) {
// Random index from 0 to i
int j = r.nextInt(i + 1);
// Swap characters at i and j
char t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
System.out.println(" " + new String(arr));
}
}
Note: This example uses the same Fisher-Yates algorithm to shuffle the elements of a character array.