In this example, I am going to show  you how to shuffle an array using Java.

Shuffle an Array :

We can shuffle an array in Java using shuffle(List<?> list) method. shuffle(List<?> list) is a static method coming from java.util.Collections class used to shuffle the given array elements.

[java]

package com.onlinetutorialspoint.javaprograms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Shuffle_Array {
    public static void main(String[] args) {
        List<String> names = new ArrayList();
        names.add("Raju");
        names.add("Rajesh");
        names.add("Chandra");
        names.add("Sachin");
        names.add("Shekhar");
        names.add("Sewagh");

        System.out.println("Before Collections.shuffle() \n");
        names.forEach(System.out::println);

        Collections.shuffle(names);

        System.out.println("After Collections.shuffle() \n");

        names.forEach(System.out::println);

    }
}
[/java]

Recommended : Java 8 forEach Example.

[box type=”success” align=”alignleft” class=”” width=”100%”]

Before Collections.shuffle()

Raju
Rajesh
Chandra
Sachin
Shekhar
Sewagh

After Collections.shuffle()

Sewagh
Sachin
Rajesh
Shekhar
Chandra
Raju

[/box]

Happy Learning 🙂