How to shuffle elements of ArrayList

In this article, we will discuss how to shuffle elements of ArrayList using Collections class’s utility shuffle() method

 

Shuffling elements of ArrayList:

Method signature:

public static void shuffle(List<Object> list);

ShuffleArrayList.java

package in.bench.resources.java.collection;

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

public class ShuffleArrayList {

	public static void main(String[] args) {

		// creating Source ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Whatsup");
		al.add("Facebook");
		al.add("Orkut");
		al.add("Instagram");
		al.add("Google");
		System.out.println("Before ArrayList Shuffle :"
				+ " Insertion Order\n\n" + al);

		// shuffling AL using Collections.shuffle(al)
		Collections.shuffle(al);
		System.out.println("\n\n\nAfter ArrayList Shuffle :"
				+ " Shuffled Order\n\n" + al);


		// again, shuffling AL using Collections.shuffle(al)
		Collections.shuffle(al);
		System.out.println("\n\n\nAgain, shuffling ArrayList :"
				+ " Shuffled Order\n\n" + al);
	}
}

Output:

Before ArrayList Shuffle : Insertion Order

[Whatsup, Facebook, Orkut, Instagram, Google]



After ArrayList Shuffle : Shuffled Order

[Orkut, Instagram, Facebook, Google, Whatsup]



Again, shuffling ArrayList : Shuffled Order

[Google, Orkut, Facebook, Whatsup, Instagram]

Note: shuffling every time produce different order

 

References:

 

Happy Coding !!
Happy Learning !!

Arrays class
How to copy elements of one ArrayList to another List