Easy Tutorial
❮ Number Asin Collection Compare ❯

Java Example - Shuffling Collections

Java Examples

The following example demonstrates how to use the Collections.shuffle() method from the Collections class to shuffle the order of elements in a collection:

Main.java File

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++)
            list.add(new Integer(i));
        System.out.println("Before shuffling:");
        System.out.println(list);

        for (int i = 1; i < 6; i++) {
            System.out.println("Shuffle " + i + ":");
            Collections.shuffle(list);
            System.out.println(list);
        }
    }
}

The output of the above code is:

Before shuffling:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Shuffle 1:
[2, 0, 5, 1, 4, 9, 7, 6, 3, 8]
Shuffle 2:
[2, 6, 4, 8, 5, 7, 9, 1, 0, 3]
Shuffle 3:
[6, 5, 1, 0, 3, 7, 2, 4, 9, 8]
Shuffle 4:
[1, 3, 8, 4, 7, 2, 0, 6, 5, 9]
Shuffle 5:
[3, 0, 7, 9, 5, 8, 4, 2, 1, 6]

Java Examples

❮ Number Asin Collection Compare ❯