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:
- Begin with an array, such as [1, 2, 3, 4, 5].
- Initialize a List with a type parameter of Integer and convert the array to a list using
Arrays.asList()
. - Utilize the
Collections.shuffle()
method to randomly rearrange the elements within the list. - Convert the shuffled list back to an array to access the newly arranged elements.
- 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]