How to shuffle an ArrayList using Java

Introduction

In this example we will see how to shuffle an ArrayList using Java programming language. We will use shuffle() method from Collections class to shuffle the ArrayList. We will also create our own method to shuffle the ArrayList.

Shuffle means rearrange the elements of the ArrayList by sliding them over each other quickly. So we will basically swap or randomize the positions of the elements in the ArrayList. To calculate the random positions of the ArrayList, we will use random() method on the maximum size of the existing ArrayList.

Prerequisites

At least Java 8

Shuffle ArrayList

Now we will see how to shuffle ArrayList using any one of the following ways.

Use Collection’s shuffle()

The simple way to shuffle the ArrayList is to use the shuffle() method from Collections class.

We first define a list of string values, then apply shuffle() method to shuffle the List.

On each execution of the below code snippets every time you may get different orders of the string values in the ArrayList.

List<String> list = Arrays.asList("gei", "jh", "hg", "iyu", "sffd");

Collections.shuffle(list);

Create Custom Method

Next we will create custom method or our own method to shuffle the List elements.

In the below code snippets we use Random class to generate random integer values for determining the index value of the ArrayList position.

We are using generic type of List so that any type of data can be used with the List.

public static <T> void shuffleList(List<T> l) {
	int n = l.size();
	Random random = new Random();
	random.nextInt();

	for (int i = 0; i < n; i++) {
		int change = i + random.nextInt(n - i);
		swap(l, i, change);
	}
}

private static <T> void swap(List<T> l, int i, int change) {
	T helper = l.get(i);
	l.set(i, l.get(change));
	l.set(change, helper);
}

Test the Program

Create main method to test the program.

public static void main(String[] args) {
	List<String> list = Arrays.asList("gei", "jh", "hg", "iyu", "sffd");

	Collections.shuffle(list);

	list.stream().forEach(System.out::println);

	System.out.println("------------------");

	shuffleList(list);

	list.stream().forEach(System.out::println);
}

Running the above main method will give you something similar to the below output:

sffd
iyu
gei
hg
jh
------------------
sffd
jh
gei
iyu
hg

Remember on each execution of the above main method you may get different orders of the string values in the output.

Source Code

Download

Thanks for reading.

Related posts

Leave a Comment