.shuffle()
Published Jul 18, 2022
Contribute to Docs
The Collections.shuffle()
method randomizes the order of elements in a List
.
Syntax
import java.util.*;
Collections.shuffle(myList);
myList
will have the order of its elements randomized.
Example
The following example creates an ArrayList
then uses Collections.shuffle()
to reorder the elements:
import java.util.*;public class Main {public static void main(String[] args) {ArrayList<String> food = new ArrayList<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");System.out.println(food);Collections.shuffle(food);System.out.println(food);Collections.shuffle(food);System.out.println(food);}}
This will output something similar to the following:
[Cabbage, Pizza, Sausage, Potatoes, Salad][Sausage, Salad, Cabbage, Pizza, Potatoes][Potatoes, Pizza, Salad, Sausage, Cabbage]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours