Collections FrameworkJava-Collection-Examples

How to shuffle the elements in a List via Java

Posted On
Posted By admin

In this blog post, I will be explaining how you can shuffle list via Java.  Consider the following code snippet:

package learnjava.collections;

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

public class ShuffleDemo {

public static void main(String[] args) {
List<Integer> input = new ArrayList<Integer>();
input.add(3);
input.add(9);
input.add(5);
input.add(15);
input.add(11);

System.out.println("Before shuffling:"+input);
Collections.shuffle(input);
System.out.println("After shuffling:"+input);

}

}

 

This code uses the Collections.shuffle method. The Collections class contains static utility methods that operate on collections like List, Set etc.  When the Collections.shuffle is invoked, it shuffles the input list randomly. The return type of this method is void, so the input list is modified. When you run this code, it will print output similar to the following:

Before shuffling:[3, 9, 5, 15, 11]
After shuffling:[15, 11, 3, 9, 5]

Note that since the shuffling is random, each time you run the code a different output will be printed.

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment