Sunday, March 31, 2024

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

Hello guys, if you have a List of numbers and you want to shuff it but don't know how then you have come to the right place. Shuffling is an important technique which is used quite a lot on coding games like number guessing games and card games., 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 
        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 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.

3. It's worth noting that the shuffle() method modifies the original list in place, so there's no need to assign the result back to the list. If you want to shuffle an array, you can convert it to a list using Arrays.asList() and then shuffle it.


That's all about how to randomize objects stored in a list in Java. As I said earlier, shuffling can be useful in various scenarios like randomizing quiz questions, shuffling a deck of cards, or randomizing the order of items in a playlist.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.