In this post under Java Collections, I will show with example how to randomly shuffle elements of a list.
Below is the complete code for your reference.
Main class
1 package core.collection;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6
7 public class ShuffleListDemo {
8 public static void main(String[] args) {
9 List<Integer> integerList = new ArrayList<>(0);
10 integerList.add(1);
11 integerList.add(2);
12 integerList.add(3);
13 integerList.add(4);
14 integerList.add(5);
15
16 System.out.println("Before shuffling: " + integerList);
17
18 Collections.shuffle(integerList);
19
20 System.out.println("After shuffling: " + integerList);
21 }
22 }
In the above code, at line 9 I create an list containing integer elements and populate it.
At line 28, I call “Collections” static method “shuffle” and pass the list as an argument.
This static method “shuffle” randomly shuffle the elements.
In this way we can shuffle the list elements.