Close

Java Collections - Collections.shuffle() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Methods:

public static void shuffle(List<?> list)

Randomly reorders the specified list using a default internal java.util.Random instance.



public static void shuffle(List<?> list,
                           Random rnd)

Randomly reorders the specified list using the specified Random.


Examples


package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ShuffleExample {

public static void main(String... args) {
List<String> list = Arrays.asList("one", "two", "three", "four");
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
}
}

Output

[one, two, three, four]
[four, two, one, three]




package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class ShuffleExample2 {

public static void main(String... args) {
List<String> list = Arrays.asList("one", "two", "three", "four");
System.out.println(list);
Collections.shuffle(list, new Random(2));
System.out.println(list);
}
}

Output

[one, two, three, four]
[four, two, one, three]




See Also