Tutorial

How to Shuffle an Array in Java

Published on August 3, 2022
author

Pankaj

How to Shuffle an Array in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

There are two ways to shuffle an array in Java.

  1. Collections.shuffle() Method
  2. Random Class

1. Shuffle Array Elements using Collections Class

We can create a list from the array and then use the Collections class shuffle() method to shuffle its elements. Then convert the list to the original array.

package com.journaldev.examples;

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

public class ShuffleArray {

	public static void main(String[] args) {

		Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7 };

		List<Integer> intList = Arrays.asList(intArray);

		Collections.shuffle(intList);

		intList.toArray(intArray);

		System.out.println(Arrays.toString(intArray));
	}
}

Output: [1, 7, 5, 2, 3, 6, 4] Note that the Arrays.asList() works with an array of objects only. The concept of autoboxing doesn’t work with generics. So you can’t use this way to shuffle an array for primitives.

2. Shuffle Array using Random Class

We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.

package com.journaldev.examples;

import java.util.Arrays;
import java.util.Random;

public class ShuffleArray {

	public static void main(String[] args) {
		
		int[] array = { 1, 2, 3, 4, 5, 6, 7 };
		
		Random rand = new Random();
		
		for (int i = 0; i < array.length; i++) {
			int randomIndexToSwap = rand.nextInt(array.length);
			int temp = array[randomIndexToSwap];
			array[randomIndexToSwap] = array[i];
			array[i] = temp;
		}
		System.out.println(Arrays.toString(array));
	}
}

Output: [2, 4, 5, 1, 7, 3, 6]

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 10, 2020

I also noticed that issue… implementation 2 will not give a uniform shuffle. The random index for the swap should be picked in the range of already shuffled items only.

- Reader

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 8, 2020

    The second one is wrong. It will end up to non uniform distribution.

    - Peter

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 24, 2019

      Your second implementation is not uniformly random (for example, the sequence 7,1,2,3,4,5,6 is abnormally unlikely to be generated) use the Fisher-Yates algorithm instead.

      - Shuffle Guy

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Featured on Community

        Get our biweekly newsletter

        Sign up for Infrastructure as a Newsletter.

        Hollie's Hub for Good

        Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

        Become a contributor

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        Welcome to the developer cloud

        DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

        Learn more
        DigitalOcean Cloud Control Panel