- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to shuffle an array in Java?
Declare a string array and add elements in the form of letters −
String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" };
Convert the above array to list −
List<String>list = Arrays.asList(letters);
Now, create a shuffled array using the Random class object and generate the random letters with nextInt() −
int len = list.size(); System.out.println("Shuffled array..."); for (int i = 0; i < letters.length; i++) { int index = new Random().nextInt(len); String shuffle = list.get(index); System.out.println(shuffle); }
Example
import java.util.Arrays; import java.util.List; import java.util.Random; public class Demo { public static void main(String[] args) { String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" }; System.out.println("Initial array = "+Arrays.toString(letters)); List<String>list = Arrays.asList(letters); int len = list.size(); System.out.println("Shuffled array..."); for (int i = 0; i < letters.length; i++) { int index = new Random().nextInt(len); String shuffle = list.get(index); System.out.println(shuffle); } } }
Output
Initial array = [P, Q, R, S, T, U, V, W, X, Y, Z] Shuffled array... P X S X W S V R Y Q R
Advertisements
To Continue Learning Please Login
Login with Google