Java Programming Tutorials

Java programming tutorials with many code examples!

Java randomly shuffle

Problem:

How in Java randomly shuffle an array or List? This common problem can be solved with Java Collections Framework as in the following example.

Solution:

In java.util.Collections class there are two methods to do shuffling:

  1. Collections.shuffle(List) – uses new Random() as randomness source
  2. Collections.shuffle(List, Random) – for custom Random source

Both shuffle a List as can be seen in the following Java example:

package com.farenda.java;

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

public class CollectionsShuffle {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        System.out.println("Numbers: " + numbers);

        Collections.shuffle(numbers);
        System.out.println("Shuffled: " + numbers);

        Collections.shuffle(numbers);
        System.out.println("Shuffled again: " + numbers);

        Collections.shuffle(numbers, new Random());
        System.out.println("Shuffled with Random: " + numbers);
    }
}

To shuffle an array use Arrays.asList() to use it as an ArrayList and the use Collections.shuffle(List) as in the example. Pretty simple, no? :-)

Every invocation of the method does shuffling as can be seen in the following output:

Numbers: [1, 2, 3, 4, 5]
Shuffled: [1, 3, 4, 5, 2]
Shuffled again: [2, 1, 3, 5, 4]
Shuffled with Random: [1, 2, 4, 3, 5]
Share with the World!