How to randomize elements in List in Java using shuffle method

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  java.util.Random object, which can be used to randomize elements. Since this method except a List, you can also pass it to LinkedList, VectorCopyOnWriteArrayList and others, which doesn't implement RandomAccess method. In such cases, this method convert list to 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 dice if you are developing any board game which requires dice e.g. Ludo.



Java Program to shuffle elements in List

Here is the sample Java program to randomize a list of Integers. 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.

If you are interested to learn more about shuffling collections, you can also check Java Generics and Collection by Maurice Naftaline, one of the most comprehensive guide of Java Collection Framework.



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 Random class which again changed the order of elements inside list.

How to shuffle list of objects in Java


Important Points about shuffling 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 Random object to other shuffle methods.

2) For List implementations which don't implement RandomAccess interface, this method first converts them to 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 object should implement Comparable or anything, you can basically shuffle the list of any object in Java.

If you are curious to learn more about List data structure in Java and how to do things with List, then you can also check out my following tutorials the on same topic :
  • How to add elements at first and last position of linked list in Java? [solution]
  • How to convert a Map to a List in Java? [solution]
  • How to convert List to Set in Java? [solution]
  • How to sort a List into ascending and descending order in Java? [solution]
  • How to iterate over List in Java? [solution]
  • How to sort ArrayList in descending order in Java? [solution]
  • How to convert an array a to list and set in Java? [solution]

No comments:

Post a Comment