Write a Java program to shuffle elements in a array list


The program starts by creating an ArrayList of String type named list_col and adding eight elements to it using the add() method of ArrayList. The elements added to the list are "Black", "Blue", "Green", "Orange", "Pink", "Purple", "White", and "Yellow". Then, the program prints the elements of the list using the println() method of System.out object.

After that, the program shuffles the elements of the list using the shuffle() method of the Collections class. The shuffled list is printed again using the println() method of System.out object.

This is because the shuffle() method of the Collections class is used to shuffle the elements of the list. The shuffled list is printed using the println() method of System.out object. The order of the elements in the shuffled list may be different each time the program is executed because the shuffle() method randomly shuffles the elements.

Source Code

import java.util.*;
public class Shuffle_ArrayList
{
	public static void main(String[] args)
	{
		List<String> list_col = new ArrayList<String>();
		list_col.add("Black");
		list_col.add("Blue");    
		list_col.add("Green");
		list_col.add("Orange");
		list_col.add("Pink");
		list_col.add("Purple");
		list_col.add("White");
		list_col.add("Yellow");		
		System.out.println("Before Shuffling :" + list_col);  
		Collections.shuffle(list_col);
		System.out.println("After Shuffling :" + list_col); 
	}
}

Output

Before Shuffling :[Black, Blue, Green, Orange, Pink, Purple, White, Yellow]
After Shuffling :[Purple, Blue, Yellow, White, Orange, Black, Pink, Green]

Example Programs