Java – How to shuffle an ArrayList

In Java, you can use Collections.shuffle to shuffle or randomize a ArrayList

TestApp.java

package com.mkyong.utils;

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

public class TestApp {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("A", "B", "C", "D", "1", "2", "3");

        //before shuffle
        System.out.println(list);

        // again, same insert order
        System.out.println(list);

        // shuffle or randomize
        Collections.shuffle(list);
        System.out.println(list);
        System.out.println(list);

        // shuffle again, different result
        Collections.shuffle(list);
        System.out.println(list);

    }

}

Output


[A, B, C, D, 1, 2, 3]
[A, B, C, D, 1, 2, 3]

[2, B, 3, C, 1, A, D]
[2, B, 3, C, 1, A, D]

[C, B, D, 2, 3, A, 1]

References

  1. Collections.shuffle JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
banjo Recent comment authors
newest oldest most voted
banjo
Guest
banjo

Thanks