Open In App

How to Shuffle the Elements of Array in Java?

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, rearranging an array’s items in a random sequence is known as shuffling the elements. This might be helpful in situations when you want to randomize data for testing, develop sorting algorithms, or create randomized gaming decks.

Let us check the topic with the basic method shuffle() Method mentioned below.

Syntax of shuffle() Method

public static void shuffle(List mylist)

Example to shuffle the elements of an array in Java

Below is the program to shuffle the elements of the array in Java:

Java




// Java Program to shuffle the 
// elements of an array
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
  
public class ArrayShuffleExample {
    public static void main(String[] args) {
        // Creating an array of integers
        Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
        // Converting the array to a list
        List<Integer> numberList = Arrays.asList(numbers);
  
        // Shuffling the list
        Collections.shuffle(numberList);
  
        // Converting the list back to an array
        Integer[] shuffledNumbers = numberList.toArray(new Integer[0]);
  
        // Displaying the shuffled array
        System.out.println("Shuffled Array: " + Arrays.toString(shuffledNumbers));
    }
}


Output

Shuffled Array: [8, 6, 7, 3, 2, 5, 1, 10, 4, 9]






Explaination of the above Program:

  • To convert the array to a List, use the Arrays.asList() function.
  • The List’s items are then shuffled using the Collections.shuffle() function.
  • Lastly, toArray() is used to transform the List back into an array.

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads