How to Shuffle List in Java Language

Shuffle List in Java

In this example, We will show you about, How to Shuffle List in Java Program. This example was tested and output has been shared in the same post.

ListShuffle.java

package com.dineshkrish.collections;

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

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class ListShuffle {

	public static void main(String[] args) {
		
		// Defining List Object
		List<String> list = new ArrayList<String>();
		
		// Adding Elements to List
		list.add("Item 1");
		list.add("Item 2");
		list.add("Item 3");
		list.add("Item 4");
		list.add("Item 5");
		list.add("Item 6");
		list.add("Item 7");
		list.add("Item 8");
		list.add("Item 9");
		list.add("Item 10");
		
		System.out.println("Before shuffleing");
		System.out.println("-----------------");
		System.out.println(list); // Printing

		// Shuffle list using Collections.shuffle() method
		Collections.shuffle(list);

		System.out.println("\nAfter shuffleing");
		System.out.println("-----------------");
		System.out.println(list); // Printing
		
	}
}

Output

Before shuffleing
—————–
[Item 1, Item 2, Item 3, Item 4, Item 5, Item 6, Item 7, Item 8, Item 9, Item 10]

After shuffleing
—————–
[Item 5, Item 1, Item 3, Item 9, Item 7, Item 6, Item 8, Item 10, Item 4, Item 2]

References

1. java.util.Collections API JavaDocs
2. Collections.shuffle() method