Tutorialspoint

1 Answer
Samual Sam

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...\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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.