How to Shuffle Arrays Using Collections | Java Interview Questions And Answers

In this tutorial, we will discuss How to Shuffle Arrays Using Java Collections. This Java Interview question is asked to check your knowledge of collections and array concepts.

To shuffle an array in Java using collections, you can follow these steps:

  1. Begin with an array, such as [1, 2, 3, 4, 5].
  2. Initialize a List with a type parameter of Integer and convert the array to a list using Arrays.asList().
  3. Utilize the Collections.shuffle() method to randomly rearrange the elements within the list.
  4. Convert the shuffled list back to an array to access the newly arranged elements.
  5. Print the values of the shuffled array using Arrays.toString().

Java program

package TestAutomationCentral;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ShuffleArraysUsingCollections {
    public static void main(String[] args) {
        //TestAutomationCentral.com
        Integer[] arr = {1, 2, 3, 4, 5};
        List<Integer> list = Arrays.asList(arr);
        Collections.shuffle(list);
        list.toArray(arr);
        System.out.println(Arrays.toString(arr));
    }
}

output:

[4, 1, 2, 3, 5]
Share

Leave a Reply