How to shuffle a list
Short answer
Collections.shuffle() puts the list in random order:
void main() {
var cards = new ArrayList<>(List.of("A", "K", "Q", "J", "10"));
Collections.shuffle(cards);
IO.println(cards);
}Output:
[A, Q, K, 10, J]The order is different on every run.
A repeatable result
Pass a Random with a fixed seed — the shuffle will be the same:
void main() {
var numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5));
Collections.shuffle(numbers, new Random(42));
IO.println(numbers);
}Output:
[2, 3, 4, 5, 1]A random element
To pick one element, you do not need to shuffle the whole list:
void main() {
var prizes = List.of("book", "mug", "t-shirt");
String prize = prizes.get(new Random().nextInt(prizes.size()));
IO.println(prize);
}Output:
mugCommon mistake
Shuffling an unmodifiable list:
void main() {
Collections.shuffle(List.of(1, 2, 3));
}Output:
Exception in thread "main" java.lang.UnsupportedOperationExceptionCopy it into new ArrayList<>(...).
Functions used in this recipe
- Collections.shuffle() — Shuffles list elements into a random order.
- Random — A random number generator: integers in a range, decimals, booleans.