To shuffle a list in Java, you can use the Collections.shuffle
method provided by the Java standard library.
In this example,
numbers
with integer values.Collections.shuffle
method on the list object numbers
.shuffle
method randomly rearranges the elements in the list in place.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.shuffle(numbers);
System.out.println("Shuffled list: " + numbers);
}
}
Shuffled list: [3, 1, 5, 4, 2]
In this example,
words
with string values.Collections.shuffle
method on the list object words
.shuffle
method randomly rearranges the elements in the list in place.import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("apple", "banana", "cherry", "date", "elderberry"));
Collections.shuffle(words);
System.out.println("Shuffled list: " + words);
}
}
Shuffled list: [cherry, elderberry, apple, banana, date]
In this tutorial, we learned How to Shuffle a List in Java language with well detailed examples.