How to shuffle list elements in Java


On this page, we are going to shuffle or randomize elements of List in Java. In this example, we randomize the ArrayList elements.

Using Collections.shuffle we can shuffle or randomize ArrayList elements.

public static void shuffle(List<?> list)

Throws: UnsupportedOperationException – if the specified list or its list-iterator does not support the set operation.

SuffleListElements.java
package org.websparrow;

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

public class SuffleListElements {
	public static void main(String[] args) {

		List<String> myList = new ArrayList<>();
		try {

			myList.add("Java");
			myList.add("Struts");
			myList.add("jQuery");
			myList.add("Spring");
			myList.add("Oracle");
			myList.add("MySQL");

			System.out.println("Before suffle the list\n" + myList + "\n");

			Collections.shuffle(myList);
			System.out.println("After suffle the list\n" + myList + "\n");

			Collections.shuffle(myList);
			System.out.println("Again after suffle the list\n" + myList);

		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		}
	}
}

Output:

Before suffle the list
[Java, Struts, jQuery, Spring, Oracle, MySQL]

After suffle the list
[MySQL, jQuery, Spring, Oracle, Java, Struts]

Again after suffle the list
[Spring, jQuery, Oracle, Java, MySQL, Struts]

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.