How to shuffle an ArrayList in Java

Elements from an ArrayList can be shuffled using the Collection.shuffle method.

Syntax:

	Collections.shuffle( list );

Here is an example creating a List with 4 elements a, b, c and d. The content of the List is written in the output, then the List is shuffled, and the content is written one more time in the output.

Create the following java file:

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

public class CollectionsShuffleList {

    public static void main(String[] argv) {
	
	List<String> list = Arrays.asList("a", "b", "c", "d");
        System.out.println( "Before shuffling: " + list );

        // Shuffle the list
        Collections.shuffle( list );
        
        System.out.println( "After shuffling: " +list );
    }

}

The output will be:

Before shuffling: [a, b, c, d]
After shuffling: [a, c, b, d]


References:

Class Collections Javadoc

Share this article:

Recent Comments