Shuffle Elements of ArrayList in Java
Shuffling means changing the positions of ArrayList elements randomly. After shuffling, they will be in different order.
Following is the example of Shuffling ArrayList elements.
Ways to shuffle elements of ArrayList:
- Using Random class
- Using Collections.shuffle()
Method 1: Using Random class
- In this method we will be going to shuffle ArrayList element using Random class to generate random index.
- And java collections.swap() method to swap ArrayList elements.
- And one more algorithm we will be going to use that is Fisher–Yates shuffle.
Before shuffling Arraylist: 10 20 30 40 50 60 70 80 After shuffling Arraylist: 10 60 30 20 50 80 40 70
Method 2: Using Collections.shuffle()
Shuffle ArrayList Elements by using Collections.shuffle().
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.