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
Java Program to generate random elements from a given array
Let’s say the following is our array −
Integer[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
Now, we can convert it to a list before shuffling it −
List<Integer>list = Arrays.asList(arr); Collections.shuffle(list);
The above shuffling generates random elements. Display them like this −
for (Integer res: list) {
System.out.print(res + " ");
}
Example
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
public static void main(String[] args) {
Integer[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
System.out.print("Array elements...\n");
for (Integer res: arr) {
System.out.print(res + " ");
}
List<Integer>list = Arrays.asList(arr);
Collections.shuffle(list);
System.out.println("\n\nRandom elements...");
for (Integer res: list) {
System.out.print(res + " ");
}
}
}
Output
Array elements... 2 4 6 8 10 12 14 16 18 20 Random elements... 18 16 4 20 12 14 10 2 6 8
Advertisements