How to shuffle an ArrayList in Java
In this tutorial, we will learn how to shuffle or randomise an ArrayList in Java. We shall use ArrayList to implement the same. ArrayList is present in the Collections framework of the java util package. It is used to store data types dynamically. We need not define the size of the ArrayList unlike Arrays in Java. This dynamic memory allocation helps in codes that require a lot of manipulation of the array elements.
You can check this too: How to print deck of cards in Java
shuffle an ArrayList in Java
We use the collection class from the util package to perform the shuffle operation. The syntax is :
Collections.shuffle(ArrayList);
Let us illustrate using example code.
// Java program to demonstrate working of shuffle() import java.util.*; // Here, we import the util package of Java so that we can perform the shuffle operation. public class hello { //defining our class named hello public static void main(String[] args) { ArrayList<Integer> testlist = new ArrayList<Integer>(); //defining an ArrayList that takes up Integer values. We can even use other data types //adding numbers to our list in chronological order testlist.add(1); testlist.add(2); testlist.add(3); testlist.add(4); testlist.add(5); testlist.add(6); System.out.println("Original List : \n" + testlist); //printing the original list Collections.shuffle(testlist); //passing our ArrayList named 'testlist' in the shuffle operation of Collections System.out.println("\nShuffled List : \n" + testlist); //printing the shuffled list. } }
In the above program, as you can see, we have shuffled an integer ArrayList using the collection framework under the util package of Java. You can also implement the shuffle by adding byte, short, long, float, double, char, boolean or string values. Such shuffling can be used to randomise a large dataset for many purposes.
Output:
Original List : [1, 2, 3, 4, 5, 6] Shuffled List : [4, 6, 2, 1, 5, 3]
Thank you for your time and patience. Do let me know if you need anything else specifically in the comments section below.
You can also check out Working with ArrayList in Java ( Adding,Removing elements)
Leave a Reply