
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 an Array Using List in Java
In this article, we will learn how to shuffle an array using a list in Java. Shuffling an array means randomly rearranging its elements. The Java Collections framework provides the Collections.shuffle() method, which can be used to shuffle a list in place.
What is an array in Java?
An array is a collection of elements of the same type, stored in contiguous memory locations.
What is a list in Java?
A List is an ordered collection (sequence) of elements in Java. It allows duplicates and maintains the order of insertion.
Shuffling an array using a list
The following are the steps to shuffle an array using a list ?
- Step 1. Define the string array ? Initialize the array with string values: String str[] = {"A", "B", "C", "D", "E"};
String str[] = {"A", "B", "C", "D", "E"};
- Step 2. Convert the array to a list ? Convert the array to a list using Arrays.asList()
List list = Arrays.asList(str);
- Step 3. Shuffle the list ?Shuffle the list using Collections.shuffle(list) and print.
Collections.shuffle(list);
System.out.println("Shuffled the array using List = " + list.toString());
Java program to shuffle an array using a list
Below is the program to shuffle an array using a list ?
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo { public static void main(String[] args) { String str[] = {"A", "B", "C", "D", "E"}; List<String>list = Arrays.asList(str); Collections.shuffle(list); System.out.println("Shuffled the array using List = "+list.toString()); } }
Output
Shuffled the array using List = [C, B, E, D, A]
Advertisements