Collections.shuffle()
Shuffles list elements into a random order.
Available since: Java 1.2
Syntax
static void shuffle(List<?> list)
static void shuffle(List<?> list, Random rnd)Parameters
| Parameter | Type | Description |
|---|---|---|
| list | List<?> | The modifiable list. |
| rnd | Random | Optional random number generator. |
Examples
With a seeded generator the result is repeatable:
void main() {
List<Integer> cards = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
Collections.shuffle(cards, new Random(42));
IO.println(cards);
}Output:
[2, 1, 5, 6, 4, 3]Notes
Without the second argument the order differs on every run. Pass new Random(seed) when you need a reproducible result — in tests or for a repeatable deal. An unmodifiable list throws UnsupportedOperationException.
See also
- Collections.reverse() — Reverses the order of list elements in place.
- Collections.sort() — Sorts a list in place.
Related recipes
In the tutorial
- Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.