Shuffle Array in Java

Siddharth Swami Jul 27, 2021
  1. Use the random() Method to Shuffle an Array in Java
  2. Use the shuffle() Method to Shuffle an Array in Java
Shuffle Array in Java

An array is one of the fundamental data structures in Java. Java is equipped with many functions and methods to process and work on arrays.

This tutorial demonstrates how to shuffle an array in Java.

Use the random() Method to Shuffle an Array in Java

We can use the Fisher-Yates shuffle array method to shuffle a given array randomly. This method aims to start from the last element of a given array and keep swapping it with a randomly selected element in the array.

We use the Random() function from the random class to randomly pick the indexes of an array. We will be importing two classes, Random and Arrays, from the java.util library.

For example,

import java.util.Random;
import java.util.Arrays;
public class ShuffleExample
    static void rand( int array[], int a)
        // Creating object for Random class
        Random rd = new Random();
        // Starting from the last element and swapping one by one.
        for (int i = a-1; i > 0; i--) {
            // Pick a random index from 0 to i
            int j = rd.nextInt(i+1);
            // Swap array[i] with the element at random index
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        // Printing the random generated array
    public static void main(String[] args)
         int[] ar = {1, 2, 3, 4, 5, 6, 7, 8};
         int b = ar.length;
         rand (ar, b);


[5, 4, 6, 2, 8, 1, 7, 3]

Use the shuffle() Method to Shuffle an Array in Java

The shuffle() function of the Collection class takes a list given by the user and shuffles it randomly. This function is easy to use and takes lesser time than the previous method. Also, it reduces the line of codes for us.

We take an array and first convert it into a list. Then, we use the shuffle() function to shuffle this list. Finally, we change this list back to an array and print it.

See the code below.

import java.util.*;
public class ShuffleExample2{
    public static void main(String[] args){
        Integer[] array={1,3,5,7,9};
        List<Integer> list =Arrays.asList(array);


[7, 9, 3, 1, 5]

In the above array, we can see our shuffled array. It returns a new shuffled array every time.

Related Article - Java Array