How to use collections.shuffle in Java?
The Collections.shuffle method is used to randomly rearrange the elements in a specified list.
The usage instructions are as follows:
- The Collections class in the Java util package.
import java.util.Collections;
- Create a list.
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
- Randomly rearrange the order of a collection
Collections.shuffle(list);
- Print the rearranged list.
System.out.println(list);
The complete example code is as follows:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ShuffleExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Collections.shuffle(list);
System.out.println(list);
}
}
After running the code, the possible output could be:
[2, 4, 3, 1]
Note: The Collections.shuffle method will change the order of the original list. If you do not want the original list to be altered, you can first create a copy and then shuffle the copy randomly.