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

The java.util.Collections class provides shuffle() method which can be used to randomize object 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 element 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 usage e.g. shuffling 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 requires dice e.g. Ludo or Snake and Ladder.



Java Program to shuffle elements in List

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 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 
        Collections.shuffle(numbers);
        
        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);
        
    }

    
}

Output
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 Java Fundamentals: Collections by Richard Richard Warburton on 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 Collections.shuffle() method for shuffling list in Java :

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

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


That's all about how to randomize object stored in a list in Java. You can use any of those two shuffle() methods to shuffle a list of object. 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
Complete Java Masterclass
Java Fundamentals: The Java Language
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
Java In-Depth: Become a Complete Java Engineer!

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

No comments:

Post a Comment