Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
listList<?>The modifiable list.
rndRandomOptional 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

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.

Thanks for reading!

Donate to the site — we work hard for you.