How to Shuffle ArrayList in Java

How to Shuffle ArrayList in Java

In Java, if we want to shuffle an arraylist, we can call Collections.shuffle() method directly. Or we can write our own shuffle method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.*;

public class Shuffle {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("either way is too late for regrets".split(" ")));
System.out.println(list);

Collections.shuffle(list);
System.out.println(list);

shuffle(list);
System.out.println(list);
}

public static void shuffle(List<String> list) {
List<String> temp = new ArrayList<>();
Random r = new Random();
while(!list.isEmpty()) {
int loc = r.nextInt(list.size());
temp.add(list.get(loc));
list.remove(loc);
}
list.addAll(temp);
}
}

The output of the above code is:

1
2
3
[either, way, is, too, late, for, regrets]
[for, late, either, regrets, too, way, is]
[too, either, for, regrets, is, way, late]