Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
collections
shuffle
list
method

How to use the Collections.shuffle method in Java

Educative Answers Team

The Collections.shuffle method is defined in Java’s built-in java.util.Collections class. As its name suggests, the method​ shuffles the elements of a given list by randomly permuting them.

svg viewer

Code

The following code snippet creates a list of strings and then shuffles them​ randomly using Collections.shuffle:

import java.util.*;

class Program {
    public static void main( String args[] ) {
      List<String> myList = new ArrayList<String>();

      myList.add("Hippo");
      myList.add("Panda");
      myList.add("Brown Bear");
      myList.add("Koala");
      myList.add("Polar Bear");  

      System.out.println("Original list: " + myList);
      // Randomly shuffle the list.
      Collections.shuffle(myList);
      System.out.println("List after shuffle: " + myList);
    }
}

One can also define the degree of randomness with which the elements are shuffled. This can be used to make shuffling a deterministic process (if that is a requirement for the program)​. Hence, when the degree of randomness is defined,​ shuffling with a fixed random seed will always produce the same random order for a particular list. The following code snippet demonstrates the usage of shuffling with a specific degree of randomness:

import java.util.*;

class Program {
    public static void main( String args[] ) {
      List<String> myList = new ArrayList<String>();

      myList.add("Hippo");
      myList.add("Panda");
      myList.add("Brown Bear");
      myList.add("Koala");
      myList.add("Polar Bear");  
      myList.add("Elephant");
      myList.add("Owl");

      System.out.println("Original list: " + myList);
      // Randomly shuffle the list with a random number.
      Collections.shuffle(myList, new Random());
      System.out.println("List after shuffle with Random(): " + myList);
      Collections.shuffle(myList, new Random(5));
      System.out.println("List after shuffle with Random(5): " + myList);

    }
}

RELATED TAGS

java
collections
shuffle
list
method
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring