java

How to Shuffle or Randomize a list in Java

In this tutorial, we’re going to see how to Shuffle or Randomize a list in Java, here is the utility method Collections.shuffle().

This method does not create a new list, but modify the passed list:

import java.util.*;

public class Main
{
     public static void main(String []args)
     {
        List<String> list = Arrays.asList("Alex", "Emily", "Jean", "Bob");
        Collections.shuffle(list);
        System.out.println(list);
     }
}

Output:

[Emily, Alex, Bob, Jean]
 
In a second version of this method, the random generator can be specified:

import java.util.*;
import java.security.SecureRandom;

public class Main
{
     public static void main(String []args)
     {
        List<String> list = Arrays.asList("Alex", "Emily", "Jean", "Bob");
        SecureRandom random = new SecureRandom();
        Collections.shuffle(list, random);
        System.out.println(list);
     }
}

Output:

[Alex, Bob, Emily, Jean]

In the default implementation the random generator is java.util.Random.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *