Java Program to generate random elements from a given array

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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...
");       for (Integer res: arr) {          System.out.print(res + " ");       }       List<Integer>list = Arrays.asList(arr);       Collections.shuffle(list);       System.out.println("

Random 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
raja
Updated on 30-Jul-2019 22:30:25

Advertisements