Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

Saturday, July 10, 2021

How to shuffle a List in Java? Collections.shuffle() Example

The java.util.Collections class provides shuffle() method which can be used to randomize objects stored in a List in Java. Since List is an ordered collection and maintains the order on which objects are inserted into it, you may need to randomize elements if you need them in a different order. Collections.shuffle() method uses default randomness to randomize elements but you also have an overloaded version of shuffle() to provide an instance of the java.util.Random object, which can be used to randomize elements.

 Since this method except for fora List, you can also pass it to LinkedList, VectorCopyOnWriteArrayList, and others, which doesn't implement the RandomAccess method.

In such cases, this method converts lithe st to the array before shuffling to avoid quadratic performance by shuffling sequential access list.

Once shuffling is done it also converts back array to list. Shuffling has many usages like shuffling a deck of cards in a poker game simulation. You can also use shuffling to roll a dice if you are developing any board games which require dice like Ludo or Snake and Ladder.

How to Randomize or Shuffle a List in Java? Example

You can shuffle the list of any object but shuffling a sorted list of numbers makes it easy to understand by just looking at the result. In this program, I have first created a list of some integers and initialized it at the same time by using our ArrayList one-line initialization tip.

Once you got the list of integers, we have passed that list to the Collections.shuffle() method for shuffling.  It doesn't return anything but shuffles objects contained in the list. 

You can print the list before and after calling to Collections.shuffle() method to see the effect of shuffling.

Here is our  sample Java program to randomize a list of Integers:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

 * Java Program to shuffle elements of a List.
 * Collections.shuffle() is used for shuffling.
 * @author WINDOWS 8
public class RandomizeList {

    public static void main(String args[]) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
        System.out.println("list before shuffling : " + numbers);
        // shuffling the list 
        System.out.println("list after shuffling : " + numbers);
        // You can even provide your own Random instance
        // for randomizing data
        Collections.shuffle(numbers, new Random(System.nanoTime()));
        System.out.println("list after shuffling again : " + numbers);


list before shuffling : [1, 2, 3, 4, 5, 6, 7]
list after shuffling : [4, 7, 1, 5, 3, 2, 6]
list after shuffling again : [5, 2, 7, 3, 1, 6, 4]

You can see that before shuffling numbers are in the same order they were inserted into the list but after shuffling they are in some random order.  We shuffle again with our instance of the Random class which again changed the order of elements inside the list.

If you are interested to learn more about shuffling collections, you can also check these Java Collections and Stream API courses from Udemy, Coursera, and Pluralsight,  one of the most comprehensive courses on  Java Collection Framework.

How to Randomize a List in Java using Collections.shuffle() Example

Important Points about shuffling a List in Java

Here are some worth noting points about using the Collections.shuffle() method for shuffling list in Java :

1. Collections class provides overloaded shuffle() method, one uses default randomness while you can provide a Random object to other shuffle methods.

2. List implementations that don't implement the RandomAccess interface, this method first converts them to an array, shuffles them, and converts them back to the list to avoid O(n^2) performance.

That's all about how to randomize objects stored in a list in Java. You can use any of those two versions of shuffle() methods to shuffle a list of objects. There is no requirement that an object should implement Comparable or anything, you can basically shuffle the list of any object in Java.

Further Learning
How to sort an ArrayList in Java 8
How to remove duplicate elements from List in Java 8
How to sort a Map by keys in Java 8

Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.