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:

  1. The Collections class in the Java util package.
import java.util.Collections;
  1. Create a list.
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
  1. Randomly rearrange the order of a collection
Collections.shuffle(list);
  1. 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.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds