Java Collections shuffle() Method
Example
Shuffle a list:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.shuffle(cars);
System.out.println(cars);
}
}
Note: The output is different each time you run the program.
Definition and Usage
The shuffle() method puts the items of a list in a random order.
You can also give your own Random object (a random number generator) as the second argument.
Syntax
One of the following:
public static void shuffle(List list)
public static void shuffle(List list, Random rnd)
Parameter Values
| Parameter | Description |
|---|---|
| list | Required. The list to shuffle. |
| rnd | Optional. The Random object to use to pick the random order. |
Technical Details
| Returns: | No return value. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods