- 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
Shuffle or Randomize a list in Java
To shuffle a list in Java, the code is as follows −
Example
import java.util.*; public class Demo{ public static void main(String[] args){ ArrayList<String> my_list = new ArrayList<String>(); my_list.add("Hello"); my_list.add(","); my_list.add("this"); my_list.add("is"); my_list.add("a"); my_list.add("sample"); System.out.println("The original list is : \n" + my_list); Collections.shuffle(my_list); System.out.println("\n The shuffled list is : \n" + my_list); } }
Output
The original list is : [Hello, ,, this, is, a, sample] The shuffled list is : [a, is, ,, Hello, this, sample]
A class named Demo contains the main function. Here, an array list is defined and elements are added to the array list with the help of the ‘add’ function. The original list is printed, and then the ‘shuffle’ function is called on this array list. This way, the elements in the list will be shuffled and then printed on the screen.
Advertisements